3
var metricUnits = function(num) {

console.log(num.toString().length);

};

// This works, gives me 21
metricUnits(900000000000000000000);

// But this fails, gives me 5
metricUnits(9000000000000000000000);

When I invoke this function, 21 is logged to the console. However, when I add one or more zeros to the end of my input argument, 5 is printed to the console?! Why is this?

2
  • 3
    Try printing num.toString(). It should make things clearer :)
    – psmears
    Jun 17, 2015 at 12:46
  • 1
    The output of toString with one more zero is 9e+21 which has a length of 5 Jun 17, 2015 at 12:48

2 Answers 2

5

If you logged the result to the console it would be obvious. Above a certain limit, numbers are represented by scientific notation (when asking for their string representation). In your second case, 9e+21 - 5 characters

Details of the limit can be found in this question.

0
2

When the number is too big, it ends up looking like: 9e+21

So, when you do .toString().length, it will return 5.

An alternative way to count the number of digits to avoid the problem is:

var metricUnits = function(num) {
  log(Math.floor(Math.log10(num)) + 1);
};

log("900000000000000000000 =>");
metricUnits(900000000000000000000);  // 21
log("9000000000000000000000 =>");
metricUnits(9000000000000000000000); // 22

function log(msg) {
  document.body.insertAdjacentHTML(
    "beforeend",
    "<pre>" + msg + "</pre>"
  );
}

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.