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?
Asked
Active
Viewed 4.8k times
43

Sebastian Simon
- 18,263
- 7
- 55
- 75

Nathan Pitman
- 2,286
- 4
- 30
- 46
-
1Possible duplicate of [Format number to always show 2 decimal places](https://stackoverflow.com/questions/6134039/format-number-to-always-show-2-decimal-places) – Liam Aug 06 '18 at 15:28
3 Answers
110
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.

albert
- 8,112
- 3
- 47
- 63

rosscj2533
- 9,195
- 7
- 39
- 56
-
2it is not working for integers. Think that number is '258' How can we do "258.00" ? – Cihan Küsmez May 02 '15 at 12:18
-
@CihanKüsmez, 258 should work. Are you trying with '258' (a string)? – rosscj2533 May 02 '15 at 14:33
-
but how can we converts into number because its giving string . @T.J.Crowder – Mahi May 09 '17 at 11:50
-
@Mahi: Trailing zeros make no sense for a number, just a string (the *representation* of anumber). – T.J. Crowder May 09 '17 at 12:01
13
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
- 4,544
- 4
- 25
- 22
6
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.

Community
- 1
- 1

T.J. Crowder
- 1,031,962
- 187
- 1,923
- 1,875