So I have some numbers x = 320232
y = 2301
z = 12020305
. I want to round these numbers off using JavaScript so that they become x = 320000
y = 2300
z = 12000000
.
I tried Math.round
and Math.floor
but turns out that they only work with decimal values like
a = 3.1; Math.round(a); // Outputs 3
and not whole numbers.
So my question is can we round of whole numbers using JavaScript and If yes then how?
Edit: I want it to the round of to the starting 3 digit places as seen in the variables above. Like If there was another variable called c = 423841
It should round off to become c = 424000
.
CodePudding user response:
You could work with the logarithm of ten and adjust the digits.
const
format = n => v => {
if (!v) return 0;
const l = Math.floor(Math.log10(Math.abs(v))) - n 1;
return Math.round(v / 10 ** l) * 10 ** l;
};
console.log([0, -9876, 320232, 2301, 12020305, 123456789].map(format(3)));
CodePudding user response:
The solution is to first calculate how many numbers need to be rounded away, and then use that in a round.
Math.round(1234/100)*100
would round to 1200
so we can use this to round. We then only need to determan what to replace 100 with in this example.
That is that would be a 1 followed by LENGTH - 3
zeros. That number can be calculated as it is 10 to the power of LENGTH - 3
, in JS: 10 ** (length - 3)
.
var x = 320232;
var y = 2301;
var z = 12020305;
function my_round(number){
var org_number = number;
// calculate integer number
var count = 0;
if (number >= 1) count;
while (number / 10 >= 1) {
number /= 10;
count;
}
// length - 3
count = Math.round(count) - 3;
if (count < 0){
count = 0;
}
// 10 to the power of (length - 3)
var helper = 10 ** count;
return Math.round(org_number/helper)*helper;
}
alert(my_round(x));
alert(my_round(y));
alert(my_round(z));
It is not the prettiest code, though I tried to make it explainable code.
CodePudding user response:
This should work:
function roundToNthPlace(input, n) {
let powerOfTen = 10 ** n
return Math.round(input/powerOfTen) * powerOfTen;
}
console.log([320232, 2301,12020305, 423841].map(input => roundToNthPlace(input, 3)));
Output: [320000, 2000, 12020000, 424000]