Javascript 如何将数字格式化为 2 个小数位,但前提是已经有小数位?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5623096/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:06:45  来源:igfitidea点击:

How do I format a number to 2 decimal places, but only if there are already decimals?

javascriptjqueryhtmldecimal

提问by Jamison

I have a jQuery 1.5+ script, and you select a quantity in a drop-down menu (1,2,3, etc) and it multiplies that quantity by $1.50 to show you a total price. Basically - it's multiplying the quantity selected (1, 2, 3, etc) by the base price of $1.50 - BUT - I can't figure out how to display the price correctly with decimals - example: if you select a quantity of 2, the price displays correctly as $3 (no decimals). But, if you choose 1, or 3, the price displays as $1.5 / $4.5 - missing a 0 in the hundredths decimal place.

我有一个 jQuery 1.5+ 脚本,您在下拉菜单(1、2、3 等)中选择一个数量,然后将该数量乘以 1.50 美元以显示总价。基本上 - 它是将所选数量(1、2、3 等)乘以 1.50 美元的基本价格 - 但是 - 我无法弄清楚如何用小数正确显示价格 - 例如:如果您选择数量 2,价格正确显示为 3 美元(无小数)。但是,如果您选择 1 或 3,价格将显示为 1.5 美元 / 4.5 美元 - 小数点后百分之一缺少 0。

Here's the code - any idea how to show a second 0 in the case that there are not already two decimals? $3 should stay as $3, but $4.5 should become $4.50, etc - I can't get it to work without showing ALL numbers to two decimals, and that's where I'm stuck!

这是代码 - 知道如何在没有两位小数的情况下显示第二个 0 吗?3 美元应该保持为 3 美元,但 4.5 美元应该变成 4.50 美元,等等 - 如果不将所有数字显示为两位小数,我就无法让它工作,这就是我被卡住的地方!

<script type='text/javascript'>     
    $(function() {         
        $('#myQuantity').change(function() {             
            var x = $(this).val();                      
            $('#myAmount').text('$'+(x*1.5));// this is the part that isn't displaying decimals correctly!
        });     
    }); 
</script>

I'm experimenting with something like result = num.toFixed(2); but can't get it to work yet.

我正在尝试诸如 result = num.toFixed(2); 之类的东西。但还不能让它工作。

Thank you Kindly!

非常感谢你!

回答by odrm

This should do the job:

这应该可以完成这项工作:

var formattedNumber = (x * 1.5).toFixed(2).replace(/[.,]00$/, "");

回答by DGV

I suggest:

我建议:

Math.round(floatNumber*100)/100;

It automatically adds 0, 1 or 2 decimal places.

它会自动添加 0、1 或 2 个小数位。

回答by Peeter

Working example: http://jsfiddle.net/peeter/JxPZH/

工作示例:http: //jsfiddle.net/peeter/JxPZH/

$(document).ready(function() {
    $('#itemQuantitySelect_3').change(function() {
        
        var itemPrice = 1.50;
        var itemQuantity = $(this).val();
        var quantityPrice = (itemPrice * itemQuantity);
        if(Math.round(quantityPrice) !== quantityPrice) {
            quantityPrice = quantityPrice.toFixed(2);
        }
        
        $(this).next("span").html("$" + quantityPrice);

    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="/" method="post">
    <select id='itemQuantitySelect_3' name="itemQuantity_3">
        <option value='1'>1 Item</option>
        <option value='2'>2 Items</option>
        <option value='3'>3 Items</option>
    </select>
    <span>.50</span>
</form>

回答by Pointy

How about

怎么样

var str = num.toFixed(2).replace(/\.00$/, '');

回答by kennebec

if a number%1 does not return zero, it is not an integer.

如果数字%1 不返回零,则它不是整数。

//var s='123';
var s='1.2';

s=Number(s);
alert(s%1? s.toFixed(2): s);

回答by daCoda

Use this function:

使用这个功能:

//E.g. 0.5 becomes 0.50; 7 stays as 7.

function twoDecimalPlacesIfCents(amount){
    return (amount % 1 !== 0) ? amount.toFixed(2) : amount;
}

回答by Gergely Szabó

If you want more generic solution, based on odrmidea.

如果你想要更通用的解决方案,基于odrm 的想法。

function toFixed(value, fractionDigits) {
    return value.toFixed(fractionDigits).replace(/[.,](00)|0$/, '')
}

回答by user2653980

One other possibility, coerce the string into a number and leverage the fact that 0.00 is falsey to determine how it displays:

另一种可能性是,将字符串强制转换为数字,并利用 0.00 为假的事实来确定它的显示方式:

+(1.123456.toFixed(2)) || 0;
>> 1.12

Where as:

然而:

+(0.00123.toFixed(2)) || 0;
>> 0

回答by Orlandster

There's actually a much more dynamic solution to achieve this. This is useful especially when your number of digits will change.

实际上有一个更加动态的解决方案来实现这一点。这在您的位数将改变时尤其有用。

var formattedNumber = (x * 1.5).toFixed(2).replace(/\.0+$|(\.\d*[1-9])(0+)$/, "");

This will end up to this:

这将结束:

+(2.1234).toFixed(2).replace(/\.0+$|(\.\d*[1-9]);
>> 2.12

// but as mentioned it is dynamic
+(2.1234).toFixed(3).replace(/\.0+$|(\.\d*[1-9]);
>> 2.123

+(2).toFixed(3).replace(/\.0+$|(\.\d*[1-9]);
>> 2