将数字格式化为始终显示 2 位小数 [英] Format number to always show 2 decimal places

查看:18
本文介绍了将数字格式化为始终显示 2 位小数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

例子:

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

我一直在用这个:

parseFloat(num).toFixed(2);

但它将 1 显示为 1,而不是 1.00.

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

推荐答案

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

现场演示

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>

请注意,它将四舍五入到小数点后两位,因此输入 1.346 将返回 1.35.

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

这篇关于将数字格式化为始终显示 2 位小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆