Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
336 views
in Technique[技术] by (71.8m points)

javascript - 格式编号始终显示2个小数位(Format number to always show 2 decimal places)

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

(我想将数字格式化为始终显示2个小数位,并在适用的情况下四舍五入。)

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 .

(但是它显示11而不是1.00 。)

  ask by Varada translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This works fine in FF4:

(在FF4中可以正常工作:)

parseFloat(Math.round(num3 * 100) / 100).toFixed(2);

Live Demo

(现场演示)

 var num1 = "1"; document.getElementById('num1').innerHTML = parseFloat(Math.round(num1 * 100) / 100).toFixed(2); var num2 = "1.341"; document.getElementById('num2').innerHTML = parseFloat(Math.round(num2 * 100) / 100).toFixed(2); var num3 = "1.345"; document.getElementById('num3').innerHTML = parseFloat(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 .

(请注意,它将四舍五入到小数点后1.346 ,因此输入1.346将返回1.35 。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...