I’m trying to round a number up to the first two digits.
JavaScript
x
5
1
14300 -> 15000
2
1430 -> 1500
3
143 -> 150
4
14 -> 14
5
I have figured out this much:
JavaScript
1
4
1
var n = 14300;
2
n = parseFloat(Math.ceil(n).toPrecision(2));
3
console.log(n);
4
It returns 14000, but I want to round it up. Math.ceil only works to the next integer. http://jsfiddle.net/cruTY/
Note: I know I can divide n
to make it a decimal, but I want this function to work for all numbers without having to manually insert /1000
or /1000000
.
Advertisement
Answer
Here you go:
JavaScript
1
7
1
var n = 14300;
2
if (String(n).length > 2) {
3
var d = Math.pow(10, String(n).length-2);
4
n = Math.ceil(n/d)*d;
5
}
6
console.log(n);
7
What’s your requirement if String(n).length < 2
?
Alternately,
JavaScript
1
12
12
1
var n = 143;
2
var l = String(n).length;
3
if (l > 2) {
4
var p = Number(String(n).slice(0,3)) / 10;
5
n = Math.ceil(p) + '';
6
while(n.length < l) {
7
n += '0';
8
}
9
n = Number(n);
10
}
11
console.log(n);
12