Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format number to always show 2 decimal places

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.

like image 272
Varada Avatar asked May 26 '11 05:05

Varada


People also ask

How do I format Excel to only show two decimal places?

By using a button: Select the cells that you want to format. On the Home tab, click Increase Decimal or Decrease Decimal to show more or fewer digits after the decimal point.

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.

What is the number 2.738 correct to 2 decimal places?

74, which is 2 decimal places.


2 Answers

(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;  }
<span id="num1"></span>  <span id="num2"></span>  <span id="num3"></span>

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

like image 70
drudge Avatar answered Oct 08 '22 04:10

drudge


Number(1).toFixed(2);         // 1.00 Number(1.341).toFixed(2);     // 1.34 Number(1.345).toFixed(2);     // 1.34 NOTE: See andy's comment below. Number(1.3450001).toFixed(2); // 1.35 

document.getElementById('line1').innerHTML = Number(1).toFixed(2);  document.getElementById('line2').innerHTML = Number(1.341).toFixed(2);  document.getElementById('line3').innerHTML = Number(1.345).toFixed(2);  document.getElementById('line4').innerHTML = Number(1.3450001).toFixed(2);
<span id="line1"></span>  <br/>  <span id="line2"></span>  <br/>  <span id="line3"></span>  <br/>  <span id="line4"></span>
like image 29
Abel ANEIROS Avatar answered Oct 08 '22 06:10

Abel ANEIROS