Skip to content
Advertisement

JavaScript round number to first two digits?

I’m trying to round a number up to the first two digits.

14300 -> 15000
1430  -> 1500
143   -> 150
14    -> 14

I have figured out this much:

var n = 14300;
n = parseFloat(Math.ceil(n).toPrecision(2));
console.log(n);

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:

var n = 14300;
if (String(n).length > 2) {
    var d = Math.pow(10, String(n).length-2);
    n = Math.ceil(n/d)*d;
}
console.log(n);

What’s your requirement if String(n).length < 2?

Alternately,

var n = 143;
var l = String(n).length;
if (l > 2) {
  var p = Number(String(n).slice(0,3)) / 10;
  n = Math.ceil(p) + '';
  while(n.length < l) {
    n += '0';
  }
  n = Number(n);
}
console.log(n);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement