Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript intelligent rounding

I currently need to round numbers up to their nearest major number. (Not sure what the right term is here)

But see an example of what I'm trying to achieve

IE:

 13 // 20
 349 // 400
 5645 // 6000
 9892 // 10000
 13988 // 20000
 93456 // 100000
 231516 // 300000

etc. etc.

I have implemented a way of doing this but its so painful and only handles numbers up to a million and if I want it to go higher I need to add more if statements (yeah see how i implmented it :P im not very proud, but brain is stuck)

There must be something out there already but google is not helping me very much probably due to me not knowing the correct term for the kind of rounding i want to do

like image 342
Tristan Avatar asked Sep 19 '11 11:09

Tristan


1 Answers

<script type="text/javascript">
    function intelliRound(num) {
        var len=(num+'').length;
        var fac=Math.pow(10,len-1);
        return Math.ceil(num/fac)*fac;
    }
    alert(intelliRound(13));
    alert(intelliRound(349));
    alert(intelliRound(5645));
    // ...
</script>

See http://jsfiddle.net/fCLjp/

like image 60
rabudde Avatar answered Sep 20 '22 13:09

rabudde