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.

7
  • What logic are you looking for? Do you want it to always round up? Commented Sep 6, 2019 at 8:06
  • 1
    This is explained in MDN documentation Commented Sep 6, 2019 at 8:10
  • 1
    (160.325).toFixed(20) gives 160.32499999999998863132. It's floating point mathematics that is to blame here. Commented Sep 6, 2019 at 8: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); Commented Sep 6, 2019 at 8: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 Commented Sep 6, 2019 at 8:17

1 Answer 1

-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 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.