如何将数字格式化为小数点后两位,但前提是已经有小数位?

发布于 2024-10-31 08:15:13 字数 758 浏览 2 评论 0原文

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

这是代码 - 知道如何在没有两位小数的情况下显示第二个 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>

我正在尝试类似 result = num.toFixed(2); 的东西但还无法让它发挥作用。

谢谢您!

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.

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!

<script type='text/javascript'>     
    $(function() {         
        $('#myQuantity').change(function() {             
            var x = $(this).val();                      
            $('#myAmount').text('

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

Thank you Kindly!

+(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.

Thank you Kindly!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(15

寻找我们的幸福 2024-11-07 08:15:13

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

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

This should do the job:

var formattedNumber = (x * 1.5).toFixed(2).replace(/[.,]00$/, "");
泪意 2024-11-07 08:15:13

我建议:

Math.round(floatNumber*100)/100;

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

I suggest:

Math.round(floatNumber*100)/100;

It automatically adds 0, 1 or 2 decimal places.

囚我心虐我身 2024-11-07 08:15:13

工作示例: 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>$1.50</span>
</form>

Working example: 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>$1.50</span>
</form>

难忘№最初的完美 2024-11-07 08:15:13

怎么样

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

How about

var str = num.toFixed(2).replace(/\.00$/, '');
灯角 2024-11-07 08:15:13
const number = Number(Number(value).toFixed(t));

有了这个,您可以将数字转换为正确的小数位数,并且在转换回数字时,去掉所有无用的零。

const number = Number(Number(value).toFixed(t));

With this you can cast your number to the correct amount of decimal places and, when converting back to Number, get rid of all useless zeros.

何其悲哀 2024-11-07 08:15:13

使用这个函数:

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

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

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;
}
音栖息无 2024-11-07 08:15:13

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

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

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

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

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

s=Number(s);
alert(s%1? s.toFixed(2): s);
审判长 2024-11-07 08:15:13

parseFloat(Number(25).toFixed(2))

const input1 = 1;
const input2 = 1.1;
const input3 = 1.12;
const input4 = 1.123
const input5 = 1.0;
const input6 = 1.00;


const output1 = parseFloat(Number(input1).toFixed(2));
const output2 = parseFloat(Number(input2).toFixed(2));
const output3 = parseFloat(Number(input3).toFixed(2));
const output4 = parseFloat(Number(input4).toFixed(2));
const output5 = parseFloat(Number(input5).toFixed(2));
const output6 = parseFloat(Number(input6).toFixed(2));

console.log("input: " + input1 + " output: " + output1);
console.log("input: " + input2 + " output: " + output2);
console.log("input: " + input3 + " output: " + output3);
console.log("input: " + input4 + " output: " + output4);
console.log("input: " + input5 + " output: " + output5);
console.log("input: " + input6 + " output: " + output6);

`

parseFloat(Number(25).toFixed(2))

const input1 = 1;
const input2 = 1.1;
const input3 = 1.12;
const input4 = 1.123
const input5 = 1.0;
const input6 = 1.00;


const output1 = parseFloat(Number(input1).toFixed(2));
const output2 = parseFloat(Number(input2).toFixed(2));
const output3 = parseFloat(Number(input3).toFixed(2));
const output4 = parseFloat(Number(input4).toFixed(2));
const output5 = parseFloat(Number(input5).toFixed(2));
const output6 = parseFloat(Number(input6).toFixed(2));

console.log("input: " + input1 + " output: " + output1);
console.log("input: " + input2 + " output: " + output2);
console.log("input: " + input3 + " output: " + output3);
console.log("input: " + input4 + " output: " + output4);
console.log("input: " + input5 + " output: " + output5);
console.log("input: " + input6 + " output: " + output6);

`

悟红尘 2024-11-07 08:15:13
value % 1 !== 0 ? value.toFixed(2) : value;
value % 1 !== 0 ? value.toFixed(2) : value;
隔纱相望 2024-11-07 08:15:13

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

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

If you want more generic solution, based on odrm idea.

function toFixed(value, fractionDigits) {
    return value.toFixed(fractionDigits).replace(/[.,](00)|0$/, '')
}
内心荒芜 2024-11-07 08:15:13
  const getPercentage = (partialValue, totalValue) => {
    return ((100 * partialValue) / totalValue).toFixed(2).replace(/[.,]00$/, "");
  }; 

您可以只使用这个函数,并在任何您想要的地方调用它

  const getPercentage = (partialValue, totalValue) => {
    return ((100 * partialValue) / totalValue).toFixed(2).replace(/[.,]00$/, "");
  }; 

You can just use this function, and call it wherever you want to

属性 2024-11-07 08:15:13

我建议使用内置数字格式化对象的 Javascript。

https://developer.mozilla.org/ en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat

const yourNumber = 75.00
const formattedNumber = new Intl.NumberFormat('en-US', {
    style: 'currency', 
    currency: 'USD',
     maximumFractionDigits: 2, 
    minimumFractionDigits: 0, 
}).format(yourNumber)
console.log(formattedNumber); // $75

I would suggest using Javascripts built in number formatting object.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat

const yourNumber = 75.00
const formattedNumber = new Intl.NumberFormat('en-US', {
    style: 'currency', 
    currency: 'USD',
     maximumFractionDigits: 2, 
    minimumFractionDigits: 0, 
}).format(yourNumber)
console.log(formattedNumber); // $75
怕倦 2024-11-07 08:15:13

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

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

其中:

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

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

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

Where as:

+(0.00123.toFixed(2)) || 0;
>> 0
百合的盛世恋 2024-11-07 08:15:13

实际上有一个更加动态的解决方案来实现这一目标。这在您的位数发生变化时尤其有用。

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

这最终将是这样的:

+(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

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
萌吟 2024-11-07 08:15:13

我建议:

Intl.NumberFormat("en-US").format(<number>);

I would suggest:

Intl.NumberFormat("en-US").format(<number>);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文