How to parse float with two decimal places in JavaScript?

By IncludeHelp Last updated : January 27, 2024

Problem statement

Given a string, write JavaScript code to parse float with two decimal places in JavaScript.

Parsing float with two decimal places

To parse float with two decimal places, use the combination of parseFloat() and .toFixed() method. The parseFloat() method will parse the given string to float and .toFixed() method rounds the float value to a given number of digits.

Syntax

Below is the syntax to parse float with two decimal places:

parseFloat(string_value).toFixed(2);

Here, string_value is the float value (which is in string format).

// Float value as string
const str = "123.456";

// Parsing to float with two decimal digits
var result = parseFloat(str).toFixed(2);

// Printing result 
console.log("Float with two decimal digits: ", result);

Output

The output of the above code is:

Float with two decimal digits:  123.46

If the given value is float already, you can directly use the .toFixed() method to round it to two-digit value float.

Consider the below code:

// Float value as string
const value = 123.456;

// Parsing to float with two decimal digits
var result = value.toFixed(2);

// Printing result 
console.log("Float with two decimal digits: ", result);

Output:

Float with two decimal digits:  123.46
Note

Never miss to write JavaScript code inside the <script>...</script> tag.

Also Learn: Where to place JavaScript Code?

To understand the above example, you should have the basic knowledge of the following JavaScript topics:

All JavaScript Examples

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.