I would love to be able to move a decimal point 2 places across an unknown amount of numbers without using math. I know that seems weird, but finite precision causes some shifts. My javascript is not strong, but I'd really like to learn how to chop up a number and do this if it's possible. So, I'm hoping you awesome folks can help.
The problem:
Is there a way to make that a string and just always move the decimal 2 places to the right to skip the math?
Here's a fiddle too, with the codes: http://jsfiddle.net/dandenney/W9fXz/
If you want to know why I need it and want the precision, it's for this little tool that I made for getting responsive percentages without using the calculator: http://responsv.com/flexible-math
If the original number is of this type of known structure and always has at least two digits to the right of the decimal, you can do it like this:
function makePercentStr(num) {
var numStr = num + "";
// if no decimal point, add .00 on end
if (numStr.indexOf(".") == -1) {
numStr += ".00";
} else {
// make sure there's at least two chars after decimal point
while (!numStr.match(/\.../)) {
numStr += "0";
}
}
return(numStr.replace(/\.(..)/, "$1.")
.replace(/^0+/, "") // trim leading zeroes
.replace(/\.$/, "") // trim trailing decimals
.replace(/^$/, "0") // if empty, add back a single 0
+ "%");
}
Working demo with test cases: http://jsfiddle.net/jfriend00/ZRNuw/
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