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
Related
What JavaScript formula can I use to truncate a number to the nearest 50.
Example. I wanted 498 > 450
I have tried
Math.round (498, 50 )
And
Math.ceil(498, 50)
But am not getting. Please help
This may be a mixup of terminology, mixing terms like "nearest" and "truncate", neither of which quite describes what the example demonstrates.
The example you give always rounds down, never up, to the nearest custom value (in this case 50). To do that you can just subtract the result of % 50. For example:
const val = 498;
console.log(val - val % 50);
Even make it a re-usable function:
const Nearest = (val, num) => val - val % num;
console.log(Nearest(498, 50));
Divide by 50, do the operation, multiply by 50.
console.log(Math.floor(498 / 50) * 50);
console.log(Math.ceil(498 / 50) * 50);
console.log(Math.round(498 / 50) * 50);
console.log(Math.trunc(498 / 50) * 50);
You divide your number by 50, take the ceiling of that number and then multiply it by 50.
Math.ceil(value / 50) * 50;
A quick sidenote: truncate has a whole other meaning for numbers in Javascript: Math.trunc on MDN
Edit:
If you want other rounding semantics than ceil you can of course use floor (always goes to lowest multiple of 50):
Math.floor(451 / 50) * 50; // => 450
You divide by the multiple and round and then multiply by the multiple. If you want the lower bound, you use floor instead of round. If you want the upper bound, you use ceil instead of round. Look at these examples:
let x = 498;
let y = Math.round(498/50)*50;
console.log(y);
y = Math.floor(498/50)*50;
console.log(y);
y = Math.ceil(498/50)*50;
console.log(y);
To do what you want, the Remainder operator is your best friend. This will give you whatever is left over after dividing the number by the nearest number.
If your goal is to always round down, the following function would work. Just take your original number, find the remainder, and remove the remainder:
function roundDownToNearest(num, nearest){
return num - (num % nearest);
}
console.log(roundDownToNearest(498, 50))
If you always want to round up, you round down, then add the nearest amount:
function roundUpToNearest(num, nearest){
return num - (num % nearest) + nearest;
}
console.log(roundUpToNearest(498, 50))
If you want to get to the closest of the two, you could do the following. Find your remainder, then see if it's greater or less than half of your nearest value. If it's greater, round up. If less, round down.
function roundToNearest(num, nearest){
if(num % nearest > nearest / 2){
return roundUpToNearest(num, nearest);
} else {
return roundDownToNearest(num, nearest);
}
}
console.log(roundToNearest(498, 50))
console.log(roundToNearest(458, 50))
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 have a number variable that is between 0 and 100. It ccould be something like 83.333334.
I want to use Math.Round to round the number (e.g. Math.round(83.333334);). How can I do this so that the result is always divisible by five (i.e. in the set [0, 5, 10, 15... 85, 90, 95, 100])?
Divide by 5, round it, multiply by 5.
alert(Math.round(83 / 5) * 5);
jsFiddle Demo
function roundDownToMultiple(number, multiple) {
return number - (number % multiple);
}
roundDownToMultiple(86, 5); // 85
roundDownToMultiple(89, 5); // 85
roundDownToMultiple(96, 5); // 95
Use the modulus operator to "round" down your number to a multiple of 5, see the example below.
var x = Math.round(83.333334);
x = x - (x % 5);
If you'd like to "round towards zero" (and have a correct value for negative numbers aswell) use something like this:
x = Math[x < 0 ? 'ceil' : 'floor'] (x/5) * 5;
Using this Math.round(Math.floor(Math.random() * 100) / 5) * 5 You can get the Numbers divisible by 5.
100 - is the range of the Result.
Give this a try.
Math.round(val / 5) * 5;
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;
}
perc = 15/30;
//result=Math.round(perc*100)/100 //returns 28.45
$('#counter').text(perc);
$('#total').text(count);
returns back 0.5% which is suppose to be 50.00%... how do I fix this? :S
You do realize that word percent quite literally translates into "per cent" or "per 100" since cent is the latin root that's used everywhere meaning "100" or "one-hundredth".
Century (100 years)
US Cent (100th of a dollar)
Centurion (Those who commanded 100 soldiers)
Centipede (creature with 100 legs)
So 50% becomes 50 per cent becomes 50 per 100
And, since in mathematical terms, the word per means divide (miles per hour == mph == m/h) then we can distill 50% down to:
50/100
Which, surprisingly enough, is represented as the decimal number .5
15/30 = 0.5
if you want to have percent number you have to multiply it by 100.
I am a low rep user so here goes. http://en.wikipedia.org/wiki/Percentage
Treat the % sign as a constant equal to 0.01. Thus, when working with a number like 50%, treat it as 50 * 0.01 or 0.5.
0.5 = n % // I want to know what 0.5 is as a percent
0.5 / % = n * % / % // Divide both sides by the constant
0.5 / % = n // Remove the excess
0.5 / 0.01 = n // Replace the constant
50 = n // You have your answer
Just multiply by 100.