Skip to content

Parse decimal JavaScript

Use parseFloat() method to Parse decimal in JavaScript. Here is the code converting string to 2 decimal.

var twoPlacedFloat = parseFloat(yourString).toFixed(2)

The parseFloat() takes in a string value and converts it to a float. The parseFloat function will look at the first character of the string and decide whether that character is a number or not If not the parseFloat function will return NaN.

Parse decimal JavaScript

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <script>
    let str = "100.0"

    let res = parseFloat(str);
    console.log(res)
    console.log(typeof(res))

    var twoPlacedFloat = res.toFixed(2)
    console.log(twoPlacedFloat)

  </script>
</body>
</html>

Output:

Parse decimal JavaScript

More example

parseFloat(10); // 10
parseFloat("10"); // 10
parseFloat("10.33"); //  10.33
parseFloat("34 45 66"); //34
parseFloat("He was 40"); // NaN

Do comment if you have any doubts or suggestions on this Js decimal code.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading