22

In this font-size resizing tutorial:

Quick and easy font resizing

the author uses parseFloat with a second argument, which I read here:

parseFloat() w/two args

Is supposed to specify the base of the supplied number-as-string, so that you can feed it '0x10' and have it recognized as HEX by putting 16 as the second argument.

The thing is, no browser I've tested seems to do this.

Are these guys getting confused with Java?

3 Answers 3

42

No, they're getting confused with parseInt(), which can take a radix parameter. parseFloat(), on the other hand, only accepts decimals. It might just be for consistency, as you should always pass a radix parameter to parseInt() because it can treat numbers like 010 as octal, giving 8 rather than the correct 10.

Here's the reference for parseFloat(), versus parseInt().

Sign up to request clarification or add additional context in comments.

1 Comment

In strict mode, octals with a leading 0 are deprecated and produce a SyntaxError. 0oN should be used now.
3

Here's a quickie version of parseFloat that does take a radix. It does NOT support scientific notation. Undefined behavior when given strings with digits outside the radix. Also behaves badly when given too many digits after the decimal point.

function parseFloatWithRadix(s, r) {
  r = (r||10)|0;
  const [b,a] = ((s||'0') + '.').split('.');
  const l1 = parseInt('1'+(a||''), r).toString(r).length;
  return parseInt(b, r) + 
    parseInt(a||'0', r) / parseInt('1' + Array(l1).join('0'), r);
}

parseFloatWithRadix('10.8', 16) gives 16.5

gist: https://gist.github.com/Hafthor/0a60f918d50113600d7c67252e68a02d

1 Comment

Thanks. I must say the inconsistency between parseInt and parseFloat is silly. At least something like your function should be part of the standard.
-3

parseFloat can accept numbers other than decimal.

console.log(parseFloat(010)) // 8

1 Comment

This isn't actually parseFloat doing anything interesting. It's because of some number formatting in javascript that I wasn't actually familiar with: 01 == 1 , 010 == 8, 0100 == 64, 021 == 17. So octal notation is apparently used when having a leading 0: developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/…

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.