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添加尾随零。我该怎么做呢?
3 个解决方案
#1
88
You can use javascript's toFixed
method (source), you don't need jQuery. Example:
你可以使用javascript的toFixed方法(源码),你不需要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.
编辑:电子工具箱链接已经屈服于linkrot并阻止了Wayback Machine,因此没有源的工作URL。
#2
10
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
#3
3
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;
}
Edit The above is great for strings, but for your specific numeric situation, rosscj2533's answer is the better way to go.
编辑以上内容非常适合字符串,但对于您的特定数字情况,rosscj2533的答案是更好的方法。
#1
88
You can use javascript's toFixed
method (source), you don't need jQuery. Example:
你可以使用javascript的toFixed方法(源码),你不需要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.
编辑:电子工具箱链接已经屈服于linkrot并阻止了Wayback Machine,因此没有源的工作URL。
#2
10
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
#3
3
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;
}
Edit The above is great for strings, but for your specific numeric situation, rosscj2533's answer is the better way to go.
编辑以上内容非常适合字符串,但对于您的特定数字情况,rosscj2533的答案是更好的方法。