How do I convert an integer to a float in JavaScript?
Solution 1
What you have is already a floating point number, they're all 64-bit floating point numbers in JavaScript.
To get decimal places when rendering it (as a string, for output), use .toFixed()
, like this:
function intToFloat(num, decPlaces) { return num.toFixed(decPlaces); }
You can test it out here (though I'd rename the function, given it's not an accurate description).
Solution 2
toFixed(x) isn't crossed browser solution. Full solution is following:
function intToFloat(num, decPlaces) { return num + '.' + Array(decPlaces + 1).join('0'); }
Solution 3
If you don't need (or not sure about) fixed number of decimal places, you can just use
xAsString = (Number.isInteger(x)) ? (x + ".0") : (x.toString());
This is relevant in those contexts like, you have an x
as 7.0
but x.toString()
will give you "7"
and you need the string as "7.0"
. If the x happens to be a float value like say 7.1
or 7.233
then the string should also be "7.1"
or "7.233"
respectively.
Without using Number.isInteger() :
xAsString = (x % 1 === 0) ? (x + ".0") : (x.toString());
Comments
-
alexia over 4 years
I've got an integer (e.g. 12), and I want to convert it to a floating point number, with a specified number of decimal places.
Draft
function intToFloat(num, decimal) { [code goes here] } intToFloat(12, 1) // returns 12.0 intToFloat(12, 2) // returns 12.00 // and so on…
-
alexia over 13 yearsNice! I – just like the previous commenter – never knew there is a bulit-in function for that! :) I think with such a short function, there is no need to declare another function for that, it would just slow down the script.
-
Marwan about 13 years+1 Nice Realy i love it when i see many hidden features on javascript
-
Ivan Kuckir almost 11 yearsNote, that toFixed returns String, not Float
-
alexia almost 10 years
toFixed
works in the latest stable version of Chrome, Firefox, Internet Explorer and Opera. It also works in IE5/IE7/IE8/IE9/IE10 document modes (there's no IE6 document mode). The behavior is consistent. -
alexia almost 10 years@IvanKuckir Yes, but that's desirable in this case, as otherwise you couldn't differentiate between
12.0
and12.00
. -
Simon Borsky almost 10 yearstoFixed works different in IE. When you run intToFloat(1.45, 1) IE will return '1.5' and Crome or FF will return '1.4'
-
alexia almost 10 yearsI see. I didn't test that.
-
Simon Borsky over 7 yearstoFixed works different in IE and other browsers. In your approach the intToFloat(1.45, 1) in IE will return '1.5' Crome/FF will return '1.4'
-
Alexander D'Attore over 3 yearsIn rare edge cases, the integer 1 behaves unexpectedly. Using
.toFixed(N)
on the integer equal to one fixed this for me. +1