12

So I am adding and subtracting floats in javascript, and I need to know how to always take the ceiling of any number that has more than 3 decimal places. For example:

3.19 = 3.19

3.191 = 3.20

3.00000001 = 3.01

mskfisher
  • 3,291
  • 4
  • 35
  • 48
bmarti44
  • 1,247
  • 2
  • 14
  • 22

2 Answers2

24
num = Math.ceil(num * 100) / 100;

Though, due to the way floats are represented, you may not get a clean number that's to two decimal places. For display purposes, always do num.toFixed(2).

Community
  • 1
  • 1
David Tang
  • 92,262
  • 30
  • 167
  • 149
  • 1
    this worked great, thank you (it did in fact answer my question). But. . . I am probably going to take Amnon's advice do everything as integers – bmarti44 Jan 27 '11 at 14:21
  • @bmarti44, Amnon's advice is good, but a word of warning. Using integers will yield no problems when doing addition and multiplication, but don't fall into a false sense of security: the same problems will arise with division, e.g. `1/10 * 3`. But of course, depending on your application, this may not happen at all. – David Tang Jan 27 '11 at 14:28
10

Actually I don't think you want to represent dollar amounts as float, due to the same reason cited by Box9. For example, 0.1*3 != 0.3 in my browser. It's better to represent them as integers (e.g. cents).

Amnon
  • 7,652
  • 2
  • 26
  • 34
  • I believe you are right to switch the float values to integers, so I will be taking your advice. Thank you for the quick answer. – bmarti44 Jan 27 '11 at 14:23