This question already has an answer here:
Math.floor () to round down to nearest 0.5 in javascript [duplicate]
(1 answer)
Closed 3 years ago.
I do NOT want to round to the NEAREST 0.5. I want to round DOWN to the nearest 0.5 value.
I have a function from excel that I use: =FLOOR(value,0.5)
9.55 becomes 9.5
9.99 becomes 9.5
9.2 becomes 9
Etc.
Is there an equivalent in javascript? I know that Math.floor () will round down to the nearest integer. However, does anyone know of a good way to round down to the nearest 0.5 instead?
Thank you in advance
Return the whole number + 0.5, if the original decimal value is >= 0.5.
const floor = (value) => {
let wholeNumber = Math.floor(value)
return wholeNumber + ((value - wholeNumber) < 0.5 ? 0.0 : 0.5)
}
This can be modified to support nearly any fraction other than 0.5.
const assertEquals = (n1, n2, precision = 0.001) => Math.abs(n1 - n2) <= precision
/**
* Returns the largest integer less than or equal to a given number rounded down to the nearest fraction.
* #param {number} value - A positive floating-point value
* #param {number} [nearest=1.0] - A fractional value between (0.0, 1.0]
* #return A number representing the largest integer less than or equal to the specified number rounded down to the nearest fraction
*/
const floorNearest = (value, nearest = 1.0) => {
let wholeNumber = Math.floor(value)
let fraction = value - wholeNumber
let factor = Math.floor(fraction / nearest)
return wholeNumber + (nearest * factor)
}
console.log(assertEquals(floorNearest(1.50), 1))
console.log(assertEquals(floorNearest(1.25), 1))
console.log(assertEquals(floorNearest(9.55, 0.5), 9.5))
console.log(assertEquals(floorNearest(9.99, 0.5), 9.5))
console.log(assertEquals(floorNearest(9.20, 0.5), 9.0))
console.log(assertEquals(floorNearest(0.55, 0.200), 0.400))
console.log(assertEquals(floorNearest(0.55, 0.250), 0.500))
console.log(assertEquals(floorNearest(0.99, 0.333), 0.666))
.as-console-wrapper { top: 0; max-height: 100% !important; }
Related
This question already has answers here:
Javascript Random Number?
(3 answers)
Closed 3 years ago.
i am using this function to generate random number between 1000 and 100.
but here according to me, in (max - min) + min, max- min =900 and min= 100, so it should not generate numbers between 900 and 100? but it is returning numbers greater than 900 also how? I am confused. and do tell how to check the range for the numbers random function is generating? any help with this?
x = Math.floor(Math.random() * (1000 - 100) + 100);
console.log(x);
The formula for random numbers Math.random() * (max - min) + min is the correct one to get a uniformly distributed number between min and max.
max - min will give you the range in which you want to generate the random numbers. So in this case 1000 - 100 results in a range of 900.
Multiplying by Math.random() will give you a random number in the range. So, with a Math.random() producing 0.5 after multiplying you get 450.
Finally, adding min back to the random pick ensures the number you get is within bounds of min and max.
For example Math.random() produces 0.01 if we substitute in the formula we get 0.01 * (1000 - 100) = 9 which is below min. Conversely, if Math.random() produces 1 then 1 * (1000 - 100) = 900 which is the highest random number possible to get from the range and yet it's still below max. In both cases adding min to the result ensures the random number you get is within max and min
The function Math.random() returns a number between 0 and 1.
When use "Math.random() * (1000 - 100)", this part of the code generates a number between 0 and 1 then multiplies it by 900, which will give you a number between 0 and 900.
Now in the last block you do add 100 to the previously generated number which results in a number between 0 and 900 + 100, which gives a result between 100 and 1000.
function random(min, max) {
console.log("Multiplying by: " + (max - min));
console.log("And adding : " + min);
return Math.floor(Math.random() * (max - min) + min);
}
console.log(random(100, 1000));
Multiply by (1000 -200) instead as you already have +100
Because in case random number generated is anything greater than 800 you end exceeding range as you're adding 100 in it everytime
x = Math.floor(Math.random() * (1000 - 200) + 100);
console.log(x);
Thumb rule :-
Math.floor(Math.random() * - ( max - ( 2 * min ) ) + min )
As Math.random() generate floats, this need to be converted to an integer.
We can use parseInt(), but there is a shorthand, the ~~ bitwise operator. Performances are known to be excellent.
console.log(
100 + ~~(Math.random() * 800)
)
One possible alternative is the web crypto api, it might be a bit slower, but with the best randomness doable. This return an integer between 0 and 256.
console.log(
100 + ~~(crypto.getRandomValues(new Uint8Array(1))[0] * 3.13)
)
I am trying to find a way to round the sum of an array of numbers in more accurate way.
for example giving an array of [33.33, 33.33, 33.33] the sum is 99.99 in this case I don't want to round the sum to be 100.
but if the array of numbers was [33.3333 , 33.3333, 33.3333] then it should round the sum to 100.
Using Math.round() is rounding always to 100 even if you have an array of [33.22 , 33.33 , 33.33]
You could multiply before rounding to have different precision:
var a = 99.99;
var b = 99.9999;
var precision = 100;
console.log(a, Math.round(a), Math.round(a * precision) / precision);
console.log(b, Math.round(b), Math.round(b * precision) / precision);
The better solution to round off a number is demoed here
function precisionRound(number, precision) {
var factor = Math.pow(10, precision);
return Math.round(number * factor) / factor;
}
console.log(precisionRound(99.99, 2)); //99.99
console.log(precisionRound(99.9999, 2)); //100
I've rounding the number into 2 decimal places:
function round(num, decimals)
{
var factor = Math.pow(10, decimals);
return Math.round(num * factor) / factor;
} round(-5.255, 2);
-5.25
function round(num, decimals)
{
var factor = Math.pow(10, decimals);
return Math.round(num * factor) / factor;
} round(5.255, 2);
5.26
But I've observed that it is giving different result when it is positive or negative.
Why is this happening and How can this be corrected?
From the documentation:
If the fractional portion of number is 0.5 or greater, the argument is rounded to the next higher integer.
So when the fraction is exactly 0.5, it rounds up. For a negative number, this means it rounds closer to 0, for a positive number it rounds away from 0. So -0.5 rounds to 0, while 0.5 rounds to 1.
If you want symmetric rounding, you can get the number's absolute value, round that, then convert it back to the original sign:
function symmetricRound(num) {
return Math.sign(num) * Math.round(Math.abs(num));
}
Math.sign is an EcmaScript 6 addition. If you're on an older browser, use the polyfill from the documentation.
Why:
If i remembrer my maths courses (quite long ago...), 0,1,2,3&4 round to the nearest smaller value, 5,6,7,8,&9 round to the nearest greater value. 5.26 is greater than 5.255. So is -5.25 greater than -5.255.
How:
If you really need to have a behavior that is the same in absolute value, why not round the absolute value, then apply a "-1" factor if original value is <0?
How do you round down a number before the decimal points
So not 45.1 -> 45
But 47 -> 45
Or 45 -> 50
Try like this:-
Math.round(45/ 10) * 10;
var number = 45.5;
alert(Math.round(number / 5) * 5);
This rounds to nearest 5.
var number = 45.5;
alert(Math.round(number / 10) * 10);
And this to nearest 10.
There is also a function floor that rounds to lower number and ceil that rounds to higher number` for example:
var number = 45.5;
alert(Math.floor(number / 10) * 10); // This will give 40
alert(Math.ceil(number / 10) * 10); // This will give 50
Can someone give me an idea how can i round off a number to the nearest 0.5.
I have to scale elements in a web page according to screen resolution and for that i can only assign font size in pts to 1, 1.5 or 2 and onwards etc.
If i round off it rounds either to 1 decimal place or none.
How can i accomplish this job?
Write your own function that multiplies by 2, rounds, then divides by 2, e.g.
function roundHalf(num) {
return Math.round(num*2)/2;
}
Here's a more generic solution that may be useful to you:
function round(value, step) {
step || (step = 1.0);
var inv = 1.0 / step;
return Math.round(value * inv) / inv;
}
round(2.74, 0.1) = 2.7
round(2.74, 0.25) = 2.75
round(2.74, 0.5) = 2.5
round(2.74, 1.0) = 3.0
Just a stripped down version of all the above answers:
Math.round(valueToRound / 0.5) * 0.5;
Generic:
Math.round(valueToRound / step) * step;
To extend the top answer by newtron for rounding on more than only 0.5
function roundByNum(num, rounder) {
var multiplier = 1/(rounder||0.5);
return Math.round(num*multiplier)/multiplier;
}
console.log(roundByNum(74.67)); //expected output 74.5
console.log(roundByNum(74.67, 0.25)); //expected output 74.75
console.log(roundByNum(74.67, 4)); //expected output 76
Math.round(-0.5) returns 0, but it should be -1 according to the math rules.
More info: Math.round()
and Number.prototype.toFixed()
function round(number) {
var value = (number * 2).toFixed() / 2;
return value;
}
var f = 2.6;
var v = Math.floor(f) + ( Math.round( (f - Math.floor(f)) ) ? 0.5 : 0.0 );
function roundToTheHalfDollar(inputValue){
var percentile = Math.round((Math.round(inputValue*Math.pow(10,2))/Math.pow(10,2)-parseFloat(Math.trunc(inputValue)))*100)
var outputValue = (0.5 * (percentile >= 25 ? 1 : 0)) + (0.5 * (percentile >= 75 ? 1 : 0))
return Math.trunc(inputValue) + outputValue
}
I wrote this before seeing Tunaki's better response ;)
These answers weren't useful for me, I wanted to always round to a half (so that drawing with svg or canvas is sharp).
This rounds to the closest .5 (with a bias to go higher if in the middle)
function sharpen(num) {
const rem = num % 1
if (rem < 0.5) {
return Math.ceil(num / 0.5) * 0.5 + 0.5
} else {
return Math.floor(num / 0.5) * 0.5
}
}
console.log(sharpen(1)) // 1.5
console.log(sharpen(1.9)) // 1.5
console.log(sharpen(2)) // 2.5
console.log(sharpen(2.5)) // 2.5
console.log(sharpen(2.6)) // 2.5
The highest voted answer above fails for:
roundHalf(0.6) => returns 0.5
roundHalf(15.27) => returns 15.5
The fixed one is as follows:
const roundHalf = (num) => {
return Math.floor(Math.ceil(num * 2) / 2)
}
As a bit more flexible variation of the good answer above.
function roundNumber(value, step = 1.0, type = 'round') {
step || (step = 1.0);
const inv = 1.0 / step;
const mathFunc = 'ceil' === type ? Math.ceil : ('floor' === type ? Math.floor : Math.round);
return mathFunc(value * inv) / inv;
}