views:

229

answers:

3

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?

+5  A: 

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
rosscj2533
**Big** +1, did not know about `toFixed`
T.J. Crowder
Brill thanks for that. :)
Nathan Pitman
Thanks, and you're welcome. :)
rosscj2533
A: 

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.

T.J. Crowder
+3  A: 

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

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