How to round float numbers in JavaScript

In this tutorial, we will learn how to round float numbers in JavaScript.

Rounding float numbers in JavaScript

Variables used in code

  • x – float number. type Number(js)
let x = 3.14159

Rounding float numbers to the nearest integer

The built-in function Math.round() is used here.

console.log(Math.round(x))

Output:

3

Rounding float number to n decimal places

Method 1

The inbuilt function toFixed() is used here.

let n = 2
console.log(Number(parseFloat(x).toFixed(n)))

Method 2

The toFixed() method returns the float number’s string format. To avoid redundant Number – String – Number conversions we use this function.

let n = 3
function roundOf(num,pos){
    let power = 10**pos
    return Math.round(num*power)/power
}
console.log(roundOf(x,n))

Output:

3.14

Truncating float number

Truncation is numerical approximation method. It is less time-consuming than rounding, but it does not always provide the most accurate approximation to the original number.

Truncating float number to an integer

The built-in function Math.trunc() is used here.

console.log(Math.trunc(x))

Output:

3

Truncating float number after n decimal places

To complete the task, we use custom function.

let n = 3
function trunc(num,pos){
    let n = num.toString()
    return Number(n.slice(0,n.indexOf('.')+pos))
}
console.log(trunc(x,n))

Output:

3.142

 

Leave a Reply

Your email address will not be published.