0

I have a question regarding toFixed() function. I have some float numbers e.g. 160.325 and 5.325. The returned value of toFixed() function supposed to be 160.33 and 5.33 respectively but it returns 160.32 for 160.325 and 5.33 for 5.325.

I have tried in different ways,

Number(160.325).toFixed(2)
"160.32"
Number(160.326).toFixed(2)
"160.33"
Number(5.325).toFixed(2)
"5.33"
Number(160.425).toFixed(2)
"160.43"

I expect output to be 160.33 and 5.33.

Basanta Taj
  • 81
  • 1
  • 8
  • What logic are you looking for? Do you want it to always round up? – CertainPerformance Sep 06 '19 at 08:06
  • 1
    This is explained in [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed) – Matt Ellen Sep 06 '19 at 08:10
  • 1
    `(160.325).toFixed(20)` gives 160.32499999999998863132. It's floating point mathematics that is to blame here. – phuzi Sep 06 '19 at 08:11
  • A quick fix is to round them up as bigger numbers and avoid toying around with floats: `rounded = (Math.round(x * 100) / 100).toFixed(2); ` – Tritonal Sep 06 '19 at 08:13
  • toFixed() works fine here it will round if necessary. according to your example 160.325 last decimal point is 5 and mathematically no need to round this therefore function doesn't round the number – Casper Sep 06 '19 at 08:17
  • You can use celi() function and round up to two decimal points, Math.ceil(160.325 * 100) / 100 – Casper Sep 06 '19 at 08:25
  • @CertainPerformance yes it should round up for me. – Basanta Taj Sep 06 '19 at 08:47

1 Answers1

-3

MDN has added a warning for this unexpected behavior. You can read here

Floating point numbers cannot represent all decimals precisely in binary which can lead to unexpected results

Example:

2.35.toFixed(1);        // Returns '2.4'. Note it rounds up
2.55.toFixed(1);        // Returns '2.5'. Note it rounds down 
Ashish
  • 4,206
  • 16
  • 45