Skip to content

JavaScript string to float 2 decimal | Example code

  • by

Use toFixed() function to parse the string to float 2 decimal in JavaScript.

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

If you need performance (like in games):

Math.round(number * 100) / 100

It’s about 100 times as fast as parseFloat(number.toFixed(2))

Source: stackoverflow.com

Example string to float 2 decimal in JavaScript

Simple example code parse float with two decimal places. When you use toFixed, it always returns the value as a string. This sometimes complicates the code.

<!doctype html>
  <head>

    <script>
      var str = "100.999";
      var res = parseFloat(str).toFixed(2)
      console.log(res);

    </script>
  </head>
  <body>

  </body>
  </html>

Output:

JavaScript string to float 2 decimal

parseFloat 2 decimals as NUMBER

    <script>
      var str = "100.999";
      var res = Math.round(str * 100) / 100

      console.log(res)
      console.log(typeof(res));

    </script>

Output: 101

number

Do comment if you have any doubts or suggestions on this JS string to float the topic.

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

Your email address will not be published. Required fields are marked *