Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert an integer to a float in JavaScript?

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… 
like image 224
nyuszika7h Avatar asked Nov 27 '10 18:11

nyuszika7h


People also ask

Is there a float type in JavaScript?

Unlike many other programming languages, JavaScript does not define different types of numbers, like integers, short, long, floating-point etc.

What does parseFloat do in JavaScript?

The parseFloat() function is used to accept the string and convert it into a floating-point number. If the string does not contain a numeral value or If the first character of the string is not a Number then it returns NaN i.e, not a number.

What is the method used in JavaScript to convert a string to a float?

Javascript has provided a method called parseFloat() to convert a string into a floating point number. Floating numbers are nothing but decimals.


1 Answers

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

like image 132
Nick Craver Avatar answered Sep 21 '22 12:09

Nick Craver