Reputation: 2344
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 latter case, I need to add the trailing zero. How would I go about doing this?
Upvotes: 46
Views: 53024
Reputation: 1231
This can be achieved by using the Internationalization API (Intl.NumberFormat function) with a configuration object. Let's take an example
const formatter = new Intl.NumberFormat('en-US', {
minimumFractionDigits: 5
})
formatter.format(258.2) // output: 258.20000
formatter.format(258.22) // output: 258.22000
Upvotes: 5
Reputation: 9323
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.
Upvotes: 115
Reputation: 4754
Javascript has a function - toFixed - that should do what you want ... no JQuery needed.
var n = 258.2;
n.toFixed (2); // returns 258.20
Upvotes: 14
Reputation: 1074038
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.
Upvotes: 6