How to add a trailing zero to a price with jQuery

馋奶兔 提交于 2019-11-26 14:26:07

问题


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

and other times I might have

258.2

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


回答1:


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

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.




回答2:


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

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



回答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:

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.



来源:https://stackoverflow.com/questions/2433122/how-to-add-a-trailing-zero-to-a-price-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!