4.25.toFixed(1) == 4.35.toFixed(1) == 4.3 but 2.35.toFixed(1)==2.4

When the non fractional part is bigger than 4 the fractional part it is truncated to .3 but when it is smaller than 4 it is rounded to .4.

Examples:

1.nr>4:

5.35.toFixed(1) => 5.3
15.35.toFixed(1) => 15.3
131.35.toFixed(1) => 131.3

2.nr<4:

2.35.toFixed(1) =>2.4
1.35.toFixed(1) =>1.4

Is this kind of behaviour normal?

Jon Skeet
people
quotationmark

The problem is that the exact values you're calling toFixed on aren't 1.35 etc... they're the nearest IEEE-754 64-bit representation. In this case, the exact values are:

1.350000000000000088817841970012523233890533447265625
2.350000000000000088817841970012523233890533447265625
5.3499999999999996447286321199499070644378662109375
15.3499999999999996447286321199499070644378662109375

Now look at those values and work out what you'd do in terms of rounding to 1 decimal place.

Basically you're falling foul of the fact that these are floating binary point values, so the value you express in decimal isn't always the value that's actually used. It's just an approximation. In other languages the preferred alternative is to use a type which represents floating decimal point values (e.g. BigDecimal in Java or decimal in C#) but I don't know of anything similar within standard Javascript. You may find some third party libraries though.

people

See more on this question at Stackoverflow