How can I round a decimal number in Javascript to the nearest 10? My math is pretty rubbish today, it could be the 2 hour sleep :/
Some sample cases
$2823.66 = $2820
$142.11 = $140
$9.49 = $10
I understand I probably need a combination of Math.round/floor but I can't seem to get expected result.
Any help/pointers appreciated!
M
Try
Math.round(val / 10) * 10;
Use this function:
function roundTen(number)
{
return Math.round(number/10)*10;
}
alert(roundTen(2823.66));
To round a number to the nearest 10, first divide it by 10, then round it to the nearest 1, then multiply it by 10 again:
val = Math.round(val/10)*10;
This page has some details. They go the other way (e.g., rounding to the nearest 0.01) but the theory and practice are identical - multiply (or divide), round, then divide (or multiply).
10 * Math.round(val / 10)
function round(number, multiplier) {
multiplier = multiplier || 1;
return Math.round(number / multiplier) * multiplier;
}
var num1 = 2823.66;
var num2 = 142.11;
var num3 = 9.49;
console.log(
"%s\n%s\n%s", // just a formating thing
round(num1, 10), // 2820
round(num2, 10), // 140
round(num3, 10) // 10
);
Related
I have two variables one for decimal numbers and one for integer.
Now, i add the decimal numbers with each other and the integers with each other then multiply the sum of decimal numbers and the sum of the integers.
My problem now is i want to round them off to the nearest 10 000
So, if 2,54 * 40 000 = 101600 i want my div to display 110 000. Is this possible?
I never know what the sum of the decimal numbers or the integers are, i just use two variables
Math.round(101600 / 10000) * 10000 // --> 100000
Math.floor(101600 / 10000) * 10000 // --> 100000
Math.ceil(101600 / 10000) * 10000 // --> 110000
var round = 10000;
var result = round * Math.round(answer / round);
Had to do this recently. Here is a function I wrote to do this automatically.
function getRoundedZeros(value, up){
var roundto = '1';
for(i = 1;i < value.toString().length; i++){
roundto = roundto.concat('0');
}
roundto = parseInt(roundto);
if(up === true){
return Math.ceil(value / roundto) * roundto;
}else{
return Math.floor(value / roundto) * roundto;
}
}
rounded = getRoundedZeros(UNrounded, true);
I hope it helps someone :)
I'm looking for an output of
4.658227848101266 = 4.5
4.052117263843648 = 4.0
the closest I've gotten is
rating = (Math.round(rating * 4) / 4).toFixed(1)
but with this the number 4.658227848101266 = 4.8???
(Math.round(rating * 2) / 2).toFixed(1)
It's rather simple, you should multiply that number by 2, then round it and then divide it by 2:
var roundHalf = function(n) {
return (Math.round(n*2)/2).toFixed(1);
};
This works for me! (Using the closest possible format to yours)
rating = (Math.round(rating * 2) / 2).toFixed(1)
So this answer helped me. Here is a little bit o magic added to it to handle rounding to .5 or integer. Notice that the *2 and /2 is switched to /.5 and *.5 compared to every other answer.
/*
* #param {Number} n - pass in any number
* #param {Number} scale - either pass in .5 or 1
*/
var superCoolRound = function(n,scale) {
return (Math.round(n / scale) * scale).toFixed(1);
};
This is kinda late. But for someone who wants to round down to whole number or 0.5, you can try this:
function roundDown(number) {
var decimalPart = number % 1;
if (decimalPart < 0.5)
return number - decimalPart;
else
return number - decimalPart + 0.5;}
Late to this party, but I thought I would throw in a nice answer using a syntax I saw elsewhere, just in case someone comes across this in the future.
const roundDown = decimalNumber => {
return decimalNumber % 1 >= 0.5 ? +`${~~decimalNumber}.5` : ~~decimalNumber;
}
Explanation:
decimalNumber % 1 leaves you with only the decimal places
The + converts the string representation of your constructed number into a float, for consistency
~~decimalNumber drops the decimal places, leaving you with an integer
I assume you want to format the number for output and not truncate the precision. In that case, use a DecimalFormat. For example:
DecimalFormat df = new DecimalFormat("#.#");
df.format(rating);
Say we had an array [0.09, 870, 499] and we want to get array values round so: [0.1, 1000, 100]?
What have I tried:
var logarithmicRound = function(val) {
var degree = Math.round(Math.log(val) / Math.LN10);
if(Math.pow(10, degree) - val > val) {
--degree;
}
return Math.pow(10, degree);
};
console.log(logarithmicRound(0.05));
console.log(logarithmicRound(0.7));
console.log(logarithmicRound(49));
console.log(logarithmicRound(50));
console.log(logarithmicRound(400));
console.log(logarithmicRound(800));
// prints
//0.1
//1
//10
//100
//100
//1000
Yet it seems quite ugly... yet it does exactly what I need.
I use a couple of functions for rounding numbers, they might be useful.
function roundTo2(value){
return (Math.round(value * 100) / 100);
}
function roundResult(value, places){
var multiplier = Math.pow(10, places);
return (Math.round(value * multiplier) / multiplier);
}
You'll obviously need to round numbers and put into the array / extract, round, put back - not as efficient as someone elses answer may be
Assuming that you wish to round up to the nearest power of 10 (and that your example of 499 rounding to 100 is incorrect):
var rounded = myArray.map(function(n) {
return Math.pow(10, Math.ceil(Math.log(n) / Math.LN10));
});
From the given example it looks like #DuckQueen wants to round off to nearest power of 10..
Here is the algo -
1. Represent each number N in scientific notation S. Lets say S is n*10^x
2. Let A =(N - (10 power x)) and B=((10 pow x+1) - N)
3. if A<B N = 10^x otherwise N=10^(x+1)
You may assume one way or the other for the case A==B
Use this for Step 1:
How can I convert numbers into scientific notation?
Question
Does anyone know of a way to round a float to the nearest 0.05 in JavaScript?
Example
BEFORE | AFTER
2.51 | 2.55
2.50 | 2.50
2.56 | 2.60
Current Code
var _ceil = Math.ceil;
Math.ceil = function(number, decimals){
if (arguments.length == 1)
return _ceil(number);
multiplier = Math.pow(10, decimals);
return _ceil(number * multiplier) / multiplier;
}
Then elsewhere...
return (Math.ceil((amount - 0.05), 1) + 0.05).toFixed(2);
Which is resulting in...
BEFORE | AFTER
2.51 | 2.55
2.50 | 2.55
2.56 | 2.65
Multiply by 20, then divide by 20:
(Math.ceil(number*20)/20).toFixed(2)
Rob's answer with my addition:
(Math.ceil(number*20 - 0.5)/20).toFixed(2)
Otherwise it always rounds up to the nearest 0.05.
** UPDATE **
Sorry has been pointed out this is not what the orig poster wanted.
I would go for the standard of actually dividing by the number you're factoring it to, and rounding that and multiplying it back again after. That seems to be a proper working method which you can use with any number and maintain the mental image of what you are trying to achieve.
var val = 26.14,
factor = 0.05;
val = Math.round(val / factor) * factor;
This will work for tens, hundreds or any number. If you are specifically rounding to the higher number then use Math.ceil instead of Math.round.
Another method specifically for rounding just to 1 or more decimal places (rather than half a place) is the following:
Number(Number(1.5454545).toFixed(1));
It creates a fixed number string and then turns it into a real Number.
I would write a function that does it for you by
move the decimal over two places (multiply by 100)
then mod (%) that inflatedNumber by 5 and get the remainder
subtract the remainder from 5 so that you know what the 'gap'(ceilGap) is between your number and the next closest .05
finally, divide your inflatedNumber by 100 so that it goes back to your original float, and voila, your num will be rounded up to the nearest .05.
function calcNearestPointZeroFive(num){
var inflatedNumber = num*100,
remainder = inflatedNumber % 5;
ceilGap = 5 - remainder
return (inflatedNumber + ceilGap)/100
}
If you want to leave numbers like 5.50 untouched you can always add this checker:
if (remainder===0){
return num
} else {
var ceilGap = 5 - remainder
return (inflatedNumber + ceilGap)/100
}
You need to put -1 to round half down and after that multiply by -1 like the example down bellow.
<script type="text/javascript">
function roundNumber(number, precision, isDown) {
var factor = Math.pow(10, precision);
var tempNumber = number * factor;
var roundedTempNumber = 0;
if (isDown) {
tempNumber = -tempNumber;
roundedTempNumber = Math.round(tempNumber) * -1;
} else {
roundedTempNumber = Math.round(tempNumber);
}
return roundedTempNumber / factor;
}
</script>
<div class="col-sm-12">
<p>Round number 1.25 down: <script>document.write(roundNumber(1.25, 1, true));</script>
</p>
<p>Round number 1.25 up: <script>document.write(roundNumber(1.25, 1, false));</script></p>
</div>
I ended up using this function in my project, successfully:
roundToNearestFiveCents( number: any ) {
return parseFloat((Math.round(number / 0.05) * 0.05).toFixed(2));
}
Might be of use to someone wanting to simply round to the nearest 5 cents on their monetary results, keeps the result a number, so if you perform addition on it further it won't result in string concatenation; also doesn't unnecessarily round up as a few of the other answers pointed out. Also limits it to two decimals, which is customary with finance.
My solution and test:
let round = function(number, precision = 2, rounding = 0.05) {
let multiply = 1 / rounding;
return parseFloat((Math.round(number * multiply) / multiply)).toFixed(precision);
};
https://jsfiddle.net/maciejSzewczyk/7r1tvhdk/40/
Even though the OP is not explicit about banker rounding, rounding up to the nearest $0.05 (5 cents) should be compatible with banker rounding. What suggested by Arth is more accurate than the accepted answer by Rob W.
(Math.ceil(number*20 - 0.5)/20).toFixed(2)
With banker rounding, you need a basic banker rounding function as suggested at Gaussian/banker's rounding in JavaScript, and I rewrite in TypeScript:
static bankerRound(num: number, decimalPlaces?: number) {
const d = decimalPlaces || 0;
const m = Math.pow(10, d);
const n = +(d ? num * m : num).toFixed(8);
const i = Math.floor(n), f = n - i;
const e = 1e-8;
const r = (f > 0.5 - e && f < 0.5 + e) ?
((i % 2 === 0) ? i : i + 1) : Math.round(n);
return d ? r / m : r;
}
static roundTo5cents(num: number) {
const r = bankerRound(Math.ceil(num * 20 - 0.5) / 20, 2);
return r;
}
The correctness of this algorithm could be verified through MBS Online, e.g. http://www9.health.gov.au/mbs/ready_reckoner.cfm?item_num=60
I want to convert all numbers to the nearest .25
So...
5 becomes 5.00
2.25 becomes 2.25
4 becomes 4.00
3.5 becomes 3.50
Here’s an implementation of what rslite said:
var number = 5.12345;
number = (Math.round(number * 4) / 4).toFixed(2);
Multiply by 4, round to integer, divide by 4 and format with two decimals.
If speed is your concern, note that you can get about a 30% speed improvement by using:
var nearest = 4;
var rounded = number + nearest/2 - (number+nearest/2) % nearest;
From my website: http://phrogz.net/round-to-nearest-via-modulus-division
Performance tests here: http://jsperf.com/round-to-nearest
Here is a generic function to do rounding. In the examples above, 4 was used because that is in the inverse of .25. This function allows the user to ignore that detail. It doesn't currently support preset precision, but that can easily be added.
function roundToNearest(numToRound, numToRoundTo) {
numToRoundTo = 1 / (numToRoundTo);
return Math.round(numToRound * numToRoundTo) / numToRoundTo;
}
Here is #Gumbo's answer in a form of a function:
var roundNearQtr = function(number) {
return (Math.round(number * 4) / 4).toFixed(2);
};
You can now make calls:
roundNearQtr(5.12345); // 5.00
roundNearQtr(3.23); // 3.25
roundNearQtr(3.13); // 3.25
roundNearQtr(3.1247); // 3.00
function roundToInc(num, inc) {
const diff = num % inc;
return diff>inc/2?(num-diff+inc):num-diff;
}
> roundToInc(233223.2342343, 0.01)
233223.23
> roundToInc(505, 5)
505
> roundToInc(507, 5)
505
> roundToInc(508, 5)
510
Use below function, hope it helps
function roundByQuarter(value) {
var inv = 1.0 / 0.25;
return Math.round(value * inv) / inv;
}
Call the function as below, will result the nearest Quarter value, that is it will not return .32, .89, .56 but will return .25, .75, .50 decimals only.
roundByQuarter(2.74) = 2.75
roundByQuarter(2.34) = 2.25
roundByQuarter(2.94) = 3.00
roundByQuarter(2.24) = 2.25
A very good approximation for rounding:
function Rounding (number, precision){
var newNumber;
var sNumber = number.toString();
var increase = precision + sNumber.length - sNumber.indexOf('.') + 1;
if (number < 0)
newNumber = (number - 5 * Math.pow(10,-increase));
else
newNumber = (number + 5 * Math.pow(10,-increase));
var multiple = Math.pow(10,precision);
return Math.round(newNumber * multiple)/multiple;
}