21

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?

Paul T. Rawkeen
  • 3,994
  • 3
  • 35
  • 51
AmbroseChapel
  • 11,957
  • 7
  • 46
  • 68

3 Answers3

40

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().

Ry-
  • 218,210
  • 55
  • 464
  • 476
  • In [strict mode](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Deprecated_octal), octals with a leading 0 are deprecated and produce a SyntaxError. `0oN` should be used now. – Christopher Jun 22 '22 at 20:16
1

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

Hafthor
  • 16,358
  • 9
  • 56
  • 65
-3

parseFloat can accept numbers other than decimal.

console.log(parseFloat(010)) // 8
Marcel Mandatory
  • 1,447
  • 13
  • 25
  • 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: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates#octal_numbers – TarVK Jul 23 '21 at 09:17