views:

525

answers:

5

Hello, I have a question regarding toFixed() function. If I have a float e.g. - 3.123123423 and 0. How can I output it to input box with toFixed(2) so the inputbox values would be 3.12 and 0. I mean if the value is integer I want output it without trailing .00 :)

+3  A: 

As there is no difference between integers and floats in JavaScript, here is my quick'n'dirty approach:

theNumber.toFixed(2).replace(".00", "");

Or something generic:

myToFixed = function (n, digits) {
    digits = digits || 0;
    return n.toFixed(digits).replace(new RegExp("\\.0{" + digits + "}"), "");
}

myToFixed(32.1212, 2) --> "32.12"
myToFixed(32.1212, 0) --> "32"
myToFixed(32, 2) --> "32"
myToFixed(32.1, 2) --> "32.10"
Fabian Neumann
Very dirty (and very quick.)... +1
Clement Herreman
Doesn't work for 3.005 (implies it's an integer).
Mark
+2  A: 
function toFixed0d(x, d)
{
    if(Math.round(x) == x)
    {
     return x.toString();
    }else
    {
     return x.toFixed(d);
    }
}

toFixed0d(3.123123423, 2) = "3.12"
toFixed0d(0, 2) = "0"
najmeddine
+1  A: 

You don't need Math.round():

var toFixed = function(val, n) {
  var result = val.toFixed(n);
  if (result == val)
    return val.toString();
  return result;
}

toFixed(3.123, 2) --> "3.12"
toFixed(3, 2) --> "3"
Matthias
PS: Also works for *.000..0 since e.g. 3.00.toString() == "3"
Matthias
This fails for toFixed(3.10, 2) --> "3.1" but should be "3.10", I guess.
Fabian Neumann
@Fabian good point!
Matthias
A: 

Note that toFixed() is broken in IE and generally not to be relied on. Annoying but accurately-rounded replacement functions given there.

bobince
+1  A: 

Results may vary in case of other browsers. So please see this link How to write a prototype for Number.toFixed in JavaScript?

pramodc84