James2707
James2707

Reputation: 122

Round float to 2 decimals javascript but round to down

I need to round a float number in javascript, but I need to round to down in caso of 1.005. I use the function .toFixed(2) but this round to up. For example

if I have 1.005 and use toFixed(2) The result gives 1.01 but I need 1.00 There is another function to do this? thanks!

Added

I have this scenarios:

Original number | Expected number

25.0010 | 25.00

25.0050 | 25.00

25.0049 | 25.00

25.0051 | 25.01

25.0090 | 25.01

Upvotes: 0

Views: 159

Answers (1)

Snellface
Snellface

Reputation: 608

Imho the easiest way to do it is like this: where the 100 represents 2 zeroes, 1000 would be 3 zeroes and forth

Math.floor(1.235*100)/100; // Gives you 1.23

Update/Edit:
..or you can do (since your comment seemed to state you wanted something else then the original question):

Math.round(1.009 * 100)/100; // Gives you 1.01

Regarding your comment, the "correct" way to round .5 is up, meaning that rounding 1.005 to a number with a maximum of 2 decimals gives you 1.01, same as 1.009 gives you 1.01. The other thing you can do is to "cut" away decimals (meaning NO rounding), then 1.005 gives you 1.00, but 1.009 will also give you 1.00.

Upvotes: 2

Related Questions