How to change the decimal value to one digit in javascript.For eg. I have value 5 and I need to show 5.0 in my javascript function .
Asked
Active
Viewed 4,787 times
2 Answers
5
Check this Demo jsFiddle
Use toFixed()
Javascript function
JavaScript
var num = 5;
var n = num.toFixed(1);
console.log(n);
Console Output
5.0
toFixed()
Function References
Updated Answer
Above answer return string but OP's require float value, use parseFloat()
function,
Javascript
var num = 5;
var n = parseFloat(num).toFixed(1);
console.log(n);

Community
- 1
- 1

Jaykumar Patel
- 26,836
- 12
- 74
- 76
-
It works for me.But I need it as a decimal not as string. – user3458120 Jun 06 '14 at 05:03
-
oky i update my answet use parseFloat() function – Jaykumar Patel Jun 06 '14 at 05:16
2
Returns
A string representation of number 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. If number is greater than 1e+21, this method simply calls Number.prototype.toString() and returns a string in exponential notation.
Examples
var numObj = 12345.6789;
numObj.toFixed(); // Returns "12346": note rounding, no fractional part
numObj.toFixed(1); // Returns "12345.7": note rounding
numObj.toFixed(6); // Returns "12345.678900": note added zeros
(1.23e+20).toFixed(2); // Returns "123000000000000000000.00"
(1.23e-10).toFixed(2); // Returns "0.00"
2.34.toFixed(1); // Returns "2.3"
-2.34.toFixed(1); // Returns -2.3 (due to operator precedence, negative number literals don't return a string...)
(-2.34).toFixed(1); // Returns "-2.3" (...unless you use parentheses)

Edwin Dalorzo
- 76,803
- 25
- 144
- 205