Something funny I noticed about Math.floor()

Something funny I noticed about Math.floor()
0.0 0


Can anyone explain this?

`let x = 3.55;
let y = Math.floor(x); //3
let z = (x-y) 
console.log(z) // returns 0.5499999999999998 `

it really messed up an exercise I was doing earlier.
found out that you can kind of overcome it if you use the .toFixed() method, but its still making me scratch my head.

thank you campers


Have met a similar thing before. It has something to do with the fact that computers use binary numbers. So they have trouble representing some fractions accurately.
Here’s a resource:


Computers use a base2 (binary) rather than a base10 (decimal) numbering system, they can’t accurately do that calculation so they get as close as they can. Try 0.1 * 0.2, you’ll get 0.020000000000000004. Computers can’t accurately map from binary to decimal [using floating point math, which is what JS uses], they just get close enough.

You get similar things in decimal - for example, what is the decimal value of 10 ÷ 3? You can only really accurately describe it as 10/3 (ie fractionally), not as a decimal (0.333333333333333…)



This sentence isn’t accurate as stated — the key is this part:

The problem is with floating point math, not with binary. Binary can easily represent numbers of an arbitrary size to an arbitrary degree of precision, as long as you have enough memory.

Floating point is a very efficient way of storing numerical values that is “good enough” for most calculations most of the time. The unfortunate thing is that it’s the only numerical data type that JS natively supports. If you want a higher degree of precision in JS, you’ll have to use a specialized library.


Yeah I should have specified that earlier. Floating point is used effectively as default to represent decimals cross-language though, which is what I was [badly] trying to get across, so you see that behaviour everywhere, not just in JS, though it’s normally easier to switch to decimal/arbitrary precision numerical libraries in other languages if it’s important to do so


This is notably why you should never store currency data as a floating point.