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?
The number of trailing zeros in a non-zero base-b integer n equals the exponent of the highest power of b that divides n. For example, 14000 has three trailing zeros and is therefore divisible by 1000 = 103, but not by 104. This property is useful when looking for small factors in integer factorization.
However, in decimal fractions strictly between −1 and 1, the leading zeros digits between the decimal point and the first nonzero digit are necessary for conveying the magnitude of a number and cannot be omitted, while trailing zeros – zeros occurring after the decimal point and after the last nonzero digit – can be ...
To add trailing zeros to a string in Python, the easiest way is with the + operator. You can also use the Python string ljust() function to add trailing zeros to a string. One last way is with the format() function. When working with strings, the ability to easily modify the values of the variables easily is valuable.
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.
Javascript has a function - toFixed - that should do what you want ... no JQuery needed.
var n = 258.2; n.toFixed (2); // returns 258.20
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With