如何使用 jQuery 向价格添加尾随零

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2433122/
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-26 13:30:20  来源:igfitidea点击:

How to add a trailing zero to a price with jQuery

jqueryzerotrailing

提问by Nathan Pitman

So I have a script which returns a price for a product. However the price may or may not include trailing zeros so sometimes I might have:

所以我有一个脚本可以返回产品的价格。然而,价格可能包括也可能不包括尾随零,所以有时我可能有:

258.22

258.22

and other times I might have

其他时候我可能有

258.2

258.2

In the later case I need to add the trailing zero with jQuery. How would I go about doing this?

在后一种情况下,我需要使用 jQuery 添加尾随零。我该怎么做呢?

回答by rosscj2533

You can use javascript's toFixedmethod (source), you don't need jQuery. Example:

您可以使用 javascript 的toFixed方法(source),您不需要 jQuery。例子:

var number = 258.2;    
var rounded = number.toFixed(2); // rounded = 258.20

Edit: Electric Toolbox link has succumbed to linkrot and blocks the Wayback Machine so there is no working URL for the source.

编辑:Electric Toolbox 链接已屈服于链接腐烂并阻止了 Wayback Machine,因此源没有可用的 URL。

回答by dbrown0708

Javascript has a function - toFixed- that should do what you want ... no JQuery needed.

Javascript 有一个函数 - toFixed- 可以做你想做的事……不需要 JQuery。

var n = 258.2;
n.toFixed (2);  // returns 258.20

回答by T.J. Crowder

I don't think jQuery itself has any string padding functions (which is what you're looking for). It's trivial to do, though:

我不认为 jQuery 本身有任何字符串填充函数(这就是你要找的)。不过,这很简单:

function pad(value, width, padchar) {

    while (value.length < width) {
        value += padchar;
    }
    return value;
}

EditThe above is great for strings, but for your specific numeric situation, rosscj2533's answeris the better way to go.

编辑以上对字符串非常有用,但对于您的特定数字情况,rosscj2533 的答案是更好的方法。