0

To start with you need...

function m(n,d){x=(''+n).length,p=Math.pow,d=p(10,d)
x-=x%3
return Math.round(n*d/p(10,x))/d+" kMGTPE"[x/3]}

Then calling like so...

// m( ANY NUMBER HERE or VAR LIKE I USE,HOW DECIMAL PLACES)
m(110000,2)

However instead of the above's result of 0.11M, I would like it to display 110k.

1 Answers1

0

What you have there is an example of an overly optimized script, lets make it more developer friendly an readable

function metricPrefix(rawNumber,decimalPlaces){
    var sufixes= " kMFGPE";
    var numberLength =(''+n).length;
    decimalPlaces=Math.pow(10,d); //raise 10 to the number of decimal places
    var modLen = numberLength - numberLength%3;
    var sufix = sufixes[modLen/3];
return Math.round(rawNumber*decimalPlaces/decimalPlaces(10,modLen))/decimalPlaces+ sufix;
}

Now it's easier to work with. We can see the issue is that we need to adjust for when the string is divisible by 3, so lets fix that.

function metricPrefix(rawNumber,decimalPlaces){
        var sufixes= " kMFGPE";        
        var numberLength =(''+rawNumber).length;
        decimalPlaces=Math.pow(10,decimalPlaces); //raise 10 to the number of decimal places
        //THis is the change
        //If the length is divisable by 3 take 3 off the length
        var modLen = numberLength%3 == 0 ? numberLength - 3 - (numberLength%3)  :  numberLength - (numberLength%3);
        console.log(modLen);
        var sufix = sufixes[(modLen/3)]
        console.log(sufix)
    return Math.round(rawNumber*decimalPlaces/Math.pow(10,modLen))/decimalPlaces+ sufix;
    }

$(document).ready(function(){
    $("#result").html(metricPrefix(110000,2));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="result"></div>
Jon P
  • 19,442
  • 8
  • 49
  • 72