Skip to content Skip to sidebar Skip to footer

Limiting Large Numbers

Simple question, how do I go about limiting a large number so it stays between 0-100. For Example: 8976382 would convert too 89 My attempt: Math.min(Math.max(8976382, 1), 100)

Solution 1:

What you have (the min/max method) isn't going to convert 8976382 into 89, but into 100 instead.

A simple algorithm (for positive numbers anyway, and assuming the upper end of the range is exclusive, so it's 0..99 inclusive) would be:

while num >= 100:
    num = int(num / 10)

That should be easily convertible into any procedural language, such as the Javascript:

var num = 8976382;
while (num >= 100) {
    num = Math.floor(num / 10);
}
alert(num);

which gives you 89 as requested.

Another option is to use the substring operation to grab the first (up to) two characters.

var num = 8976382;
num = ("" + num).substr(0,2);
alert(num);

If the range you want is actually 0..100 inclusive at both ends, use > rather than >= in the first solution. In that case, the substring method becomes problematic since you have to detect strings starting with 100 specially.

Solution 2:

Try This:

+(8976382 + "").slice(0,2);

Solution 3:

It seems you just need first two digits of a number (excluding 100). If that is so, then you can get those first two digits using substr or other javascript string manipulating methods like substring.

var num = 8976382;
var result = ("" + num).substr(0,2);

// Output => "89"

This works even if you have only one digit. Say:

var num = 3;
var result = ("" + 3).substr(0, 2);

// Output => "3"

Later if you want to convert that output string to number, use parseInt or just add + to the above code:

var num = 8976382;
var result = +("" + 8976382).substr(0,2);

// Output => 89

NOTE: If there is a possibility for negative numbers then consider adding condition as if( num > 0).

Solution 4:

It looks like you want the first two digits of a number when that number is greater than 100.

So I would do it like this in Javascript:

var y = 8976382;
var x = y < 100 ? y : parseInt((''+y).substring(0, 2));

And like this in Java:

int y = 8976382;
int x = y < 100 ? y : Integer.parseInt(String.valueOf(y).substring(0, 2));

Solution 5:

x = 8976382;y = parseInt((x+'').slice(0,2));

Post a Comment for "Limiting Large Numbers"