Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format a number to two decimal places

Give me a native (no jQuery, Prototype, etc. please) JavaScript function that converts numbers as follows:

input:  0.39, 2.5,  4.25, 5.5,  6.75, 7.75, 8.5
output: 0.39, 2.50, 4.25, 5.50, 6.75, 7.75, 8.50

E.g., in Ruby, I'd do something like this:

>> sprintf("%.2f", 2.5)
=> "2.50"

The output may be a number or a string. I don't really care because I'm just using it to set innerHTML.

Thank you.

like image 258
ma11hew28 Avatar asked Jan 05 '11 23:01

ma11hew28


People also ask

How do you convert a number to two decimal places?

Rounding a decimal number to two decimal places is the same as rounding it to the hundredths place, which is the second place to the right of the decimal point. For example, 2.83620364 can be round to two decimal places as 2.84, and 0.7035 can be round to two decimal places as 0.70.

How do I format to 2 decimal places in Word?

Click the Table Tools' Layout tab, select Data and then click Formula. Click the Number Format menu and select 0.00 for two decimals.


2 Answers

input = 0.3;
output = input.toFixed(2);
//output: 0.30
like image 160
Eric Fortis Avatar answered Oct 19 '22 16:10

Eric Fortis


You can use the toFixed() method on Number objects:

var array = [0.39, 2.5,  4.25, 5.5,  6.75, 7.75, 8.5], new_array = [];
for(var i = 0, j = array.length; i < j; i++) {
    if(typeof array[i] !== 'number') continue;
    new_array.push(array[i].toFixed(2));
}
like image 37
Jacob Relkin Avatar answered Oct 19 '22 14:10

Jacob Relkin