Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript toFixed function

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 :)

like image 609
faya Avatar asked Sep 08 '09 10:09

faya


People also ask

What does toFixed do in JavaScript?

toFixed() returns a string representation of numObj that does not use exponential notation and has exactly digits digits after the decimal place. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length.

How do I get 2 decimal places in JavaScript?

Use the toFixed() method to format a number to 2 decimal places, e.g. num. toFixed(2) . The toFixed method takes a parameter, representing how many digits should appear after the decimal and returns the result.

Does toFixed round JavaScript?

Note. The toFixed() method will round the resulting value if necessary. The toFixed() method will pad the resulting value with 0's if there are not enough decimal places in the original number. The toFixed() method does not change the value of the original number.


3 Answers

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"
like image 89
Fabian Avatar answered Sep 28 '22 10:09

Fabian


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"
like image 28
Matthias Avatar answered Sep 28 '22 10:09

Matthias


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"
like image 42
manji Avatar answered Sep 28 '22 12:09

manji