Syntax of parseFloat() Method
The syntax of the parseFloat() method can easily be defined as:
In this syntax:
- returnVar is the variable in which the return value from the parseFloat() method is stored
- string: It is the string that is to be parsed into a floating-point value
Working of parseFloat() Method
The parseFloat() working is quite simple. It checks the string character by point. If they are numbers, they are parsed as numbers. If numbers follow a full stop, it parses them as the decimal point followed by numbers. However, if the string’s first character is a non-numeric value, then it would simply return a NaN.
The important thing to note here is that if there are even ten decimal places, it will parse those ten decimal places. That is why restricting a parsed value to a fixed number of decimal places is not possible with the parseFloat() method alone.
The toFixed() method
The toFixed() method (as mentioned above) is also a built-in method of JavaScript whose working is very straightforward. It reduces the number of decimal places from a floating-point value to a fixed amount. The number of decimal places is passed inside its arguments. However, it doesn’t change the original value. Therefore, you need to store the return value in a variable.
Parsing a Value to Two Decimal Points
To perform the task at hand, start by creating a string value that contains a floating-point value with more than two decimal places with the following line:
After that, simply pass this variable stringValue parseFloat() variable and store the return value in a new variable:
At this point, if this parsedValue is printed on the terminal using the console log function like:
The result would be:
This is not what is required.
Therefore, apply the toFixed() method on this parsedValue variable with the help of a dot operator and set the argument equal to 2 as:
After that, simply pass this result variable to the console log function:
Executing the program will show the following result on the terminal:
It is clear that the number has been parsed with only two decimal places. Also, there is one more thing, you can apply the parseFloat() method and the toFixed() in a single statement like:
The output will be:
It produced the same result with fixed two decimal places.
Wrap-up
JavaScript provides two built-in methods which are the parseFloat() and the toFixed(). Users can use these methods in combination with each other to restrict the parsed value to two decimal places. This article has explained the working of both to achieve the task at hand with the help of an example.
from https://ift.tt/mw3yRQY
0 Comments