Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Second argument to parseFloat in JavaScript?

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?

like image 536
AmbroseChapel Avatar asked Dec 18 '11 23:12

AmbroseChapel


People also ask

How parseFloat () works in JavaScript?

The parseFloat() function is used to accept the string and convert it into a floating-point number. If the string does not contain a numeral value or If the first character of the string is not a Number then it returns NaN i.e, not a number.

Does parseFloat return a string?

The parseFloat() method parses a value as a string and returns the first number.

What is the difference between parseFloat and number JavaScript?

parseFloat is a bit slower because it searches for first appearance of a number in a string, while the Number constuctor creates a new number instance from strings that contains numeric values with whitespace or that contains falsy values.

What is parseInt and parseFloat in JavaScript?

JavaScript provides two methods for converting non-number primitives into numbers: parseInt() and parseFloat() . As you may have guessed, the former converts a value into an integer whereas the latter converts a value into a floating-point number.


2 Answers

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

like image 102
Ry- Avatar answered Sep 18 '22 17:09

Ry-


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

like image 40
Hafthor Avatar answered Sep 20 '22 17:09

Hafthor