Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DRY out engineering notation implementation

Tags:

javascript

This my code:

function engineeringNotation(number) {
    var space = ' ';

    // Giga
    if(number >= 1e10)
        return (number / 1e9).toFixed(1) + space + 'G';
    else if(number >= 1e9)
        return (number / 1e8).toFixed(0) / 10 + space + 'G';

    // Mega
    else if(number >= 1e7)
        return (number / 1e6).toFixed(1) + space + 'M';
    else if(number >= 1e6)
        return (number / 1e5).toFixed(0) / 10 + space + 'M';

    // Kilo
    else if(number >= 1e4)
        return (number / 1e3).toFixed(1) + space + 'k';
    else if(number >= 1e3)
        return (number / 1e2).toFixed(0) / 10 + space + 'k';

    // Unit
    else if(number >= 1e1)
        return (number / 1e0).toFixed(0) + space + '';
    else
        return (number / 1e-1).toFixed(0) / 10 + space + '';
}

Basically, it takes a number, and returns it in "engineering notation" to one decimal place. For example, 1234 becomes 1.2 k. I feel I'm repeating myself a lot. Can the above code be improved and DRYed out?

like image 452
Randomblue Avatar asked Jan 19 '26 21:01

Randomblue


1 Answers

Just implementing (some of) Pointy's idea, this is not the most optimal approach, but it should get you started.

function engineeringNotation(number) {
    var unitMap = {G:1e9,M:1e6,k:1e3};
    var space = ' ';
    for(var unit in unitMap) {
        if(unitMap.hasOwnProperty(unit)) {
            if(number >= unitMap[unit]*10) {
                return (number / unitMap[unit]).toFixed(1) + space + unit;
            }
            if(number >= unitMap[unit]) {
                return (number / unitMap[unit]/10).toFixed(0) / 10 + space + unit;
            }
        }
    }
}
like image 100
Frances McMullin Avatar answered Jan 22 '26 14:01

Frances McMullin



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!