51

I have a few values:

var one = 1.0000
var two = 1.1000
var three = 1.1200
var four = 1.1230

and function:

function tofixed(val)
{
   return val.toFixed(2);
}

this return:

1.00
1.10
1.12
1.12 

LIVE

I want maximum size after dot - 2, but only if numbers after for != 0. So i would like receive:

1
1.1
1.12
1.12 

How can i make it?

tckmn
  • 57,719
  • 27
  • 114
  • 156
user2565589
  • 543
  • 1
  • 4
  • 6
  • 4
    +val.toFixed(2); gives you a real Number, chopped. – dandavis Jul 09 '13 at 19:00
  • Do you know the semantic difference between `1.2` and `1.200`? The first one has a precision of 1 fraction digit and can be a rounded value of e.g. `1.23` or `1.18`. The second one has a precision of 3 fraction digits. – Wiimm Jul 04 '21 at 09:58

4 Answers4

115

.toFixed(x) returns a string. Just parse it as a float again:

return parseFloat(val.toFixed(2));

http://jsfiddle.net/mblase75/y5nEu/1/

Blazemonger
  • 90,923
  • 26
  • 142
  • 180
22

Assuming you want String outputs

function myFixed(x, d) {
    if (!d) return x.toFixed(d); // don't go wrong if no decimal
    return x.toFixed(d).replace(/\.?0+$/, '');
}
myFixed(1.0000, 2); // "1"
myFixed(1.1000, 2); // "1.1"
myFixed(1.1200, 2); // "1.12"
myFixed(1.1230, 2); // "1.12"
Paul S.
  • 64,864
  • 9
  • 122
  • 138
  • 2
    @Doorknob can you provide an example where this does this not work? – Paul S. Jul 09 '13 at 18:57
  • 2
    why make the dot optional? – dandavis Jul 09 '13 at 18:59
  • 1
    @Doorknob did you try it? That won't happen because `1200..toFixed(2)` is `"1200.00"` so the RegExp won't go beyond the `.`, cutting just the `.00` and leaving `1200`. – Paul S. Jul 09 '13 at 18:59
  • `myFixed(1e30,2)` returns `"1e+3"` instead of the correct `"1e+30"`. – Wiimm Jun 22 '21 at 12:36
  • @Wiimm yes, situations where `.toFixed` returns scientific notation aren't handled by this answer, you can add a string check for an `e` in those cases if you wish to simply pass them through – Paul S. Jul 02 '21 at 11:10
13

The "correct" way to do it is as follows:

return Math.round(num*100)/100;

If you want to truncate it to two decimal places (ie. 1.238 goes to 1.23 instead of 1.24), use floor instead of round.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
0

How about this:

parseFloat((2199.004).toFixed(2)) // 2199
B001ᛦ
  • 2,036
  • 6
  • 23
  • 31