3

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?

Kaidul
  • 15,409
  • 15
  • 81
  • 150
  • 1
    Just divide by 100, take the floor of the quotient, and multiply by 100. – Pointy Nov 25 '12 at 14:18
  • 1
    @AlvinWong I think it is not really a duplicate, in that this question is really about categorization, although the mechanism used to implement is the modulus operation. – SAJ14SAJ Nov 25 '12 at 14:26
  • So... would you like `1001 - 2000` or `1001 - 1100` for four-digit numbers? – Alvin Wong Nov 25 '12 at 14:30

2 Answers2

4

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
SAJ14SAJ
  • 1,698
  • 1
  • 13
  • 32
  • +1. My answer takes a less roundabout way than the OP, but it's stll too roundabout. This is really the right way to do it. – Ben Lee Nov 25 '12 at 14:22
  • My array value can vary in a large range. `Arr` can contain 5 or even 352626 – Kaidul Nov 25 '12 at 14:24
  • Sure... this will still categorize into centuries of 0 and 352600. If that isn't the behavior you expect, then please clarify the question. – SAJ14SAJ Nov 25 '12 at 14:28
3

How about this:

var max = parseInt(Math.max.apply(Math, arr) / 100) * 100;
var min = parseInt(Math.min.apply(Math, arr) / 100) * 100

First divide the number by 100 to get only the significant digits before the decimal point, use parseInt to truncate (removing everything after the decimal point, insignificant digits), then multiply by 100 again to get the value back to the right magnitude.

Ben Lee
  • 52,489
  • 13
  • 125
  • 145