Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to floor integer value in Javascript

It sounds weird but I need this for now.Actually I have an array like that :

var arr = new Array(123, 432, 98, 227, 764);
var max = Math.max.apply(Math, arr); //calculate max = 764
var min = Math.min.apply(Math, arr); //calculate min = 123

Now I have to make several range based on the min and max:

 100 - 200 // as the min is 123 (range 100 ~ 200) 
 201 - 300
 301 - 400
 401 - 500
 501 - 600
 601 - 700
 701 - 800 // as the min is 764 (range 700 ~ 800)

Making the range is just a loop issue.But calculating the range of min and max I implemented as :

function integerRound (digit) {
    var i = 0, msb; 
    while( digit > 0 ) {
      msb = digit % 10;
      digit = Math.floor( digit / 10 );
      i++;
    }
    while ( i > 1 ) {
      msb = msb + '0';
      i--;
    };
    return msb;
}

var lowerMin = integerRound(min); // 100
var lowerMax = integerRound(max); // 700

My question is - Is there any good way to do that in javascript or jQuery?

like image 632
Kaidul Avatar asked Nov 17 '25 12:11

Kaidul


1 Answers

Given this use case is essentially a categorization into centuries, is there some reason you cannot simply remove the extraneous part:

century = value - (value % 100)

If you really need the ranges to start at 201, and so forth, then just subtract one before doing it, and back the one to correct.

value -= 1;
century = value - (value % 100) + 1
like image 102
SAJ14SAJ Avatar answered Nov 20 '25 00:11

SAJ14SAJ



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!