Reputation: 3093
I have a number of variable length the looks something like this:
48.4532
I want to convert it to 4 digits before decimal and 2 decimal places, so the number above should be:
0048.45
I also don't want to show decimals unless they are necessary, so:
48
should become:
0048
I was able to get the fixed length, but I couldn't get the decimals to show up only if they were necessary (I don't want to show two 0's at the end).
This is how I got a fixed length:
trackPartLength = ("0000" + trackPartLength.toString()).slice(-4); // Convert to fixed length
How do I add the 2 decimal points only if they are needed?
Edit: I also just realized that if the number does have decimals with the above code, it moves the decimal point over 4 spots causing some other problems, so I'm not sure if my initial approach is a good one. I'm trying to right a fixed length function of variable fixed prefix and decimal length.
Upvotes: 2
Views: 547
Reputation: 141829
This should work:
trackPartLength = ("0000" + trackPartLength.toFixed(2)).slice(-7).replace( /\.00$/, '' );
It uses toFixed to get the two decimal points, zero pads and then removes any trailing .00
. Examples:
48.4532 -> 0048.45
48 -> 0048
6.213 -> 0006.21
12345 -> 2345
1234.56789 -> 1234.57
If the number can have more than four digits before the decimal, as in the 12345 example, you may want to make the zero padding and slice conditional, so that you don't remove leading digits from a big number. That could be done like this:
var tmp = trackPartLength.toFixed(2);
trackPartLength = (tmp.length >= 7 ? tmp : ('0000' + tmp).slice(-7)).replace( /\.00$/, '' );
Upvotes: 1