HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptCritical

Format number to always show 2 decimal places

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
placesalwaysdecimalnumberformatshow

Problem

I would like to format my numbers to always display 2 decimal places, rounding where applicable.

Examples:

number     display
------     -------
1          1.00
1.341      1.34
1.345      1.35


I have been using this:

parseFloat(num).toFixed(2);


But it's displaying 1 as 1, rather than 1.00.

Solution

(Math.round(num * 100) / 100).toFixed(2);


Live Demo



var num1 = "1";
document.getElementById('num1').innerHTML = (Math.round(num1 * 100) / 100).toFixed(2);

var num2 = "1.341";
document.getElementById('num2').innerHTML = (Math.round(num2 * 100) / 100).toFixed(2);

var num3 = "1.345";
document.getElementById('num3').innerHTML = (Math.round(num3 * 100) / 100).toFixed(2);

span {
border: 1px solid #000;
margin: 5px;
padding: 5px;
}







Note that it will round to 2 decimal places, so the input 1.346 will return 1.35.

Code Snippets

(Math.round(num * 100) / 100).toFixed(2);

Context

Stack Overflow Q#6134039, score: 1797

Revisions (0)

No revisions yet.