Use parseFloat() to parse string to float point value

Description

parseFloat() uses the following rules to convert string to float point value.

  • parseFloat() function looks at each character starting in position 0.
  • It continues to parse the string until it reaches either the end of the string or a character that is invalid in a floating-point number.
  • A decimal point is valid the first time it appears, but a second decimal point is invalid and the rest of the string is ignored, resulting in "12.34.5" being converted to 12.34.
  • parseFloat() always ignores initial zeros.
  • It will recognize floating-point with e-notation.
  • Hexadecimal numbers always become 0.
  • Because parseFloat() parses only decimal values, there is no radix mode.
  • If the string represents a whole number (2 or 2.0), parseFloat() returns an integer.

Example


var num1 = parseFloat("1234blue");    //1234 - integer
console.log(num1);/*from   w ww .j a  v a  2s.c o  m*/
var num2 = parseFloat("0xA");         //0
console.log(num2);
var num3 = parseFloat("22.5");        //22.5
console.log(num3);
var num4 = parseFloat("22.34.5");     //22.34
console.log(num4);
var num5 = parseFloat("0908.5");      //908.5
console.log(num5);
var num6 = parseFloat("3.125e7");     //31250000
console.log(num6);

The code above generates the following result.





















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions