This question already has answers here:
Rounding to nearest 100
(7 answers)
Closed 9 years ago.
I'm trying to round a number the 100.
Example:
1340 should become 1400
1301 should become 1400
and
298 should become 300
200 should stay 200
I know about Math.round but it doesn't round to the 100.
How can I do that ?
Original Answer
Use the Math.ceil function, such as:
var result = 100 * Math.ceil(value / 100);
Generalised Version
This function can be generalised as follows:
Number.prototype.roundToNearest = function (multiple, roundingFunction) {
// Use normal rounding by default
roundingFunction = roundingFunction || Math.round;
return roundingFunction(this / multiple) * multiple;
}
Then you can use this function as follows:
var value1 = 8.5;
var value2 = 0.1;
console.log(value1.roundToNearest(5)); // Returns 10
console.log(value1.roundToNearest(5, Math.floor)); // Returns 5
console.log(value2.roundToNearest(2, Math.ceil)); // Returns 2
Or with a custom rounding function (such as banker's rounding):
var value1 = 2.5;
var value2 = 7.5;
var bankersRounding = function (value) {
var intVal = Math.floor(value);
var floatVal = value % 1;
if (floatVal !== 0.5) {
return Math.round(value);
} else {
if (intVal % 2 == 0) {
return intVal;
} else {
return intVal + 1;
}
}
}
console.log(value1.roundToNearest(5, bankersRounding)); // Returns 0
console.log(value2.roundToNearest(5, bankersRounding)); // Returns 10
An example of the code running is available here.
Try this...
function roundUp(value) {
return (~~((value + 99) / 100) * 100);
}
That will round up to the next hundred - 101 will return 200.
jsFiddle example - http://jsfiddle.net/johncmolyneux/r8ryd/
Open your console to see the results.
Related
This question already has answers here:
Round number up to the nearest multiple of 3
(13 answers)
Closed 1 year ago.
I have a math problem like this:
When I enter a number, I find the nearest larger number that is divisible by a number x
Example: x = 50
Input = 20 => output = 50
Input = 67 => output = 100
Input = 200 => output = 200
Input = 289 => output = 300
Input = 999 => output = 1000
.......
I have a function below, but is there a way to make it faster?
console.log(roundNumber(199));
function roundNumber(n) {
let x = 50;
let flg = false;
while (flg === false) {
if (n > x) {
x += 50;
} else {
flg = true;
}
}
return x;
}
Yes, you can divide the input value by 50, take the "floor", add 1, and then multiply by 50.
function roundNumber(n) {
let x = 50;
return (Math.floor((n + x - 1) / x)) * 50;
}
Whether this will be much faster is kind-of irrelevant, unless for some reason you're performing this operation thousands and thousands of times over a short interval.
I have some chunks as following example:
// lowest and highest values of chunk arrays
[
[0, 945710.3843175517],
[945710.3843175517, 2268727.9557668166],
[2268727.9557668166, 14965451.25314727],
[14965451.25314727, 17890252.39415521],
[17890252.39415521, 3501296406.880383]
]
what I want to get from these chunks is something like this:
< 1.000.000
1.000.000 - 3.000.000
3.000.000 - 15.000.000
15.000.000 - 18.000.000
> 10.000.000
I will use these new numbers as a legend of an informative map.
I use a function to achieve this goal named as roundClosestLegendNumber for each value.
All numbers are positive numbers and there is no maximum limitation.
roundClosestLegendNumber(5) \\ should give 10
roundClosestLegendNumber(94) \\ should give 100
roundClosestLegendNumber(125) \\ should give 200
roundClosestLegendNumber(945710.3843175517) \\ should give 1000000
roundClosestLegendNumber(14965451.25314727) \\ should give 15000000
roundClosestLegendNumber(17890252.39415521) \\ should give 18000000
// and so on
I changed the comparison for multiplier from 10 * to 100 * to get a precision of 2 digits before the series of 0s.
var roundClosestLegendNumber = function(number) {
if(number < 10) {
return number;
}
var multiplier = 10;
while(number >= 100 * multiplier) {
multiplier = 10 * multiplier;
}
count = 1;
while(number > multiplier * count) {
count++;
}
return multiplier * count;
}
You could use significant figures, set sf (I've set mine to 3) then only the first 3 numbers are displayed.
function sigFigure(v) {
let sf = 3;
if (v >= Math.pow(10,sf)) {
let number = v.toPrecision(sf);
let numbers = number.split("e+")
return parseInt((numbers[0]*Math.pow(10,numbers[1])).toFixed(0));
} else {
return v
}
}
var array = [0, 945710.38431755, 2268727.9557668166, 14965451.25314727, 17890252.39415521, 3501296406.880383];
console.log(array.map(sigFigure));
This question already has answers here:
How to round an integer up or down to the nearest 10 using Javascript
(4 answers)
Closed 6 years ago.
How can I round an integer number in Javascript to the nearest 10? My math is pretty rubbish today :)
Some sample cases:
45 = 50
41 = 50
40 = 40
I understand I probably need a combination of Math.round/floor but I can't seem to get expected result.
Any help/pointers appreciated,
thanks
//Update: faster way
var getDozen = function (n) {
var r = n % 10;
// if its greater than 4
if (r > 4)
return n - r + 10;
//if its lower than 5, then subtract the remainder
else
return n - r;
}
console.log(getDozen(45)); // 50
var getDozen = function (n) {
var r = n % 10;
if (r > 4) return Math.ceil(n / 10) * 10;
else return Math.floor(n / 10) * 10;
}
console.log(getDozen(45)); // 50
I have different value like
5.5
13.56
45.70
58.89 (never go more than 60)
and many more ...
Suppose they are minutes. And I want their output in the round of nearest 15 division like
5.5 => 0
13.56 => 15
45.70 => 45
58.89 => 60
But I am not sure how can I achieve this rounded output. Please help me...
There is not built in method to achieve that, however you can divide your number by 15, then use round() to round to nearest integer number and finally multiply by 15 to get the actual value:
var a = 13.56;
var dividedBy15 = a / 15; // result is 0.904
var dividedAndRounded = Math.round(dividedBy15); // result is 1
var finalResult = dividedAndRounded * 15; // result is 15
Another option:
function roundToFifteen(num) {
var mod = num % 15;
if (mod < 7.5) {
return num - mod;
} else {
return num + (15 - mod);
}
}
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
<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/
One way;
var a = [13, // 20
349, // 400
5645, // 6000
9892, // 10000
13988, // 20000
93456, // 100000
231516 // 300000
]
for (var i in a) {
var num = a[i];
var scale = Math.pow(10, Math.floor(Math.log(num) / Math.LN10));
print([ num, Math.ceil(num / scale) * scale ])
}
13,20
349,400
5645,6000
9892,10000
13988,20000
93456,100000
231516,300000
The answer from #rabudde works well, but for those that need to handle negative numbers, here's an updated version:
function intelliRound(num) {
var len = (num + '').length;
var result = 0;
if (num < 0) {
var fac = Math.pow(10, len - 2);
result = Math.floor(num / fac) * fac;
}
else {
var fac = Math.pow(10, len - 1);
result = Math.ceil(num / fac) * fac;
}
return result;
}
alert(intelliRound(13));
alert(intelliRound(349));
alert(intelliRound(5645));
alert(intelliRound(-13));
alert(intelliRound(-349));
alert(intelliRound(-5645));
you can use Math.ceil function, as described here:
javascript - ceiling of a dollar amount
to get your numbers right you'll have to divide them by 10 (if they have 2 digits), 100 (if they have 3 digits), and so on...
The intelliRound function from the other answers works well, but break with negative numbers. Here I have extended these solutions to support decimals (e.g. 0.123, -0.987) and non-numbers:
/**
* Function that returns the floor/ceil of a number, to an appropriate magnitude
* #param {number} num - the number you want to round
*
* e.g.
* magnitudeRound(0.13) => 1
* magnitudeRound(13) => 20
* magnitudeRound(349) => 400
* magnitudeRound(9645) => 10000
* magnitudeRound(-3645) => -4000
* magnitudeRound(-149) => -200
*/
function magnitudeRound(num) {
const isValidNumber = typeof num === 'number' && !Number.isNaN(num);
const result = 0;
if (!isValidNumber || num === 0) return result;
const abs = Math.abs(num);
const sign = Math.sign(num);
if (abs > 0 && abs <= 1) return 1 * sign; // percentages on a scale -1 to 1
if (abs > 1 && abs <= 10) return 10 * sign;
const zeroes = `${Math.round(abs)}`.length - 1; // e.g 123 => 2, 4567 => 3
const exponent = 10 ** zeroes; // math floor and ceil only work on integer
const roundingDirection = sign < 0 ? 'floor' : 'ceil';
return Math[roundingDirection](num / exponent) * exponent;
}