Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I move a decimal in javascript without math?

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:

  • 575/960 = 0.5989583333333334 using the console
  • I would like to make that a copy and pastable percentage like: 59.89583333333334%
  • If I use math and multiply by 100, it returns 59.895833333333336 because of finite precision

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

like image 332
Dan Denney Avatar asked Dec 02 '25 19:12

Dan Denney


1 Answers

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/

like image 149
jfriend00 Avatar answered Dec 05 '25 08:12

jfriend00



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!