Open In App

How to Parse Float with Two Decimal Places in TypeScript ?

Last Updated : 12 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Typescript, parsing float with two decimal places refers to mainly converting the float number with two digits after the decimal points. There are various approaches to parse float with two decimal places in TypeScript which are as follows:

Using Math.round method

In this approach, we are using the Math.round method which is similar to the JavaScript function that rounds the number to the nearest integer. This function takes the floating number as the input and it returns the nearest integer.

Syntax:

Math.round(x: number): number;

Example: To demonstrate how the Math.round method parses the float number with two decimal places. The 123.45678 input number is been parsed with two decimal places (123.46).

Javascript




const input: number = 123.45678;
const output: number = Math.round(input * 100) / 100;
console.log(output);


Output:

123.46

Using toFixed method

In this approach, the toFixed method is used to mainly format the input number which is the specified number of digits after the decimal place.

Syntax:

number.toFixed(digits?: number): string;

Example: The below example parses the float number to two decimal places using the toFixed method, where we have given the 2 as the argument which represents the number of decimal places.

Javascript




const input: number = 123.45678;
const output: number = ((input * 100) | 0) / 100;
console.log(output);


Output:

123.46

Using Number constructor

In this approach, we are using the Number constructor to convert a numeric value to a string with a fixed number of decimal places using the toFixed method, then this constructor is used to the resulting string, which parses it back into a floating-point number with the specified precision.

Syntax:

Number(value: any): number;

Example: The below example uses the Number constructor and toFixed method to convert the number 123.45678 into a string with two decimal places and then parses it back to a floating-point number (123.46).

Javascript




const input: number = 123.45678;
const output: number = Number(input.toFixed(2));
console.log(output);


Output:

123.46

Using bitwise OR operator

In this approach, we are using the bitwise OR operator which performs the bitwise OR operation between the individual bits of the two numbers. We are changing the integer values at the binary level using this approach.

Syntax:

result = operand1 | operand2;

Example: The below example uses bitwise OR operations to round the number 123.45678 to two decimal places, resulting in 123.45.

Javascript




const input: number = 123.45678;
const output: number = ((input * 100) | 0) / 100;
console.log(output);


Output:

123.45


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads