Search This Blog

2024/03/25

Javascript: Rounding a real number(round,toFixed,parseFloat)

Math.round method rounds a real number to nearest integer.

Consider following code snippet.
Code:
let number = 34.5678
console.log(Math.round(number))

Output:
35
Explanation:
The value of number variable is rounded to the nearest integer.

How to round a real number to certain decimal places ?
In JavaScript, you can use the toFixed() method to round
a real number to a certain number of decimal places.

Code:
let num = 12.34444;
let roundedNum = num.toFixed(2);
console.log(roundedNum);
console.log(typeof roundedNum);

roundedNum = parseFloat(roundedNum);
console.log(typeof roundedNum);
Output:
12.34
string
number

Another Example:

Code:
let num = 12.34567;
let roundedNum = num.toFixed(2);
console.log(roundedNum);
console.log(typeof roundedNum);

roundedNum = parseFloat(roundedNum);
console.log(typeof roundedNum);
Output:
12.35
string

The toFixed() method converts a number into a string,
representing the number rounded to a specified number of decimal places.

parseFloat convert string to number.

parseFloat in detail:
parseFloat() is a built-in JavaScript function that parses a string
argument and returns a floating-point number. It attempts to convert
the string into a number, considering only the characters that make up
a valid number (digits, a decimal point, and an optional positive or
negative sign at the beginning).Any non-numeric characters or spaces
after the number are ignored.

Code:
let numStr3 = "ABC123";
let num3 = parseFloat(numStr3);
console.log(num3);

Output:
NaN

Explanation:since the string doesn't represent a valid number we get NaN.

Another example:
Code:
let numStr4 = " 30.75 ";
let num4 = parseFloat(numStr4);
console.log(num4);

Output:
30,75

Note:leading and trailing spaces are ignored

Another Example:
Code:
let numStr4 = "12.567$30.75#";
let num4 = parseFloat(numStr4);
console.log(num4);

Output:
12.567

No comments:

Post a Comment