11

In my code I will be accepting multiple values, for example:

8.7456
8.7
8

and I need to have them appear as

8.74
8.7
8

i.e. display up to two decimal place.

I understand that .toFixed(2) will help me with the first value, but on the 2nd and 3rd value there will be trailing zeroes that I do not want.

How to produce my desired results?

Cœur
  • 37,241
  • 25
  • 195
  • 267
peroija
  • 1,982
  • 4
  • 21
  • 37

2 Answers2

16

Use Number.toFixed to round the number up to two digits and format as a string. Then use String.replace to chop off trailing zeros:

[8.7456, 8.745, 8.74, 8.7, 8].forEach(function(num) {
  var str = num.toFixed(2).replace(/\.?0+$/, "");
  console.log(num, str);
});
Salman A
  • 262,204
  • 82
  • 430
  • 521
  • 1
    okay okay you got it, no more updates! i altered your second iteration to what you posted here (because of the `8.` result) thanks for your help! – peroija Apr 18 '12 at 19:31
  • rounding is okay, i initially didn't want to round but it turns out that I should. however, if you wanted to post an example of how to do this without rounding I am sure someone at some point will use it – peroija Apr 18 '12 at 19:35
5

Multiply by 100, floor, divide by 100.

var n = 8.7456;
var result = Math.floor(n * 100) / 100; // 8.74

Edit: if you’re looking at this question after the fact, this is probably not what you want. It satisfies the odd requirement of having 8.7456 appear as 8.74. See also the relevant comment.

Ry-
  • 218,210
  • 55
  • 464
  • 476