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 :)
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.
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.
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.
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"
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"
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With