Display the number with floating point without rounding in JavaScript

Sometime you need to display the result with floating points of the some mathematical calculation without rounding off such as you have the value 12.56667, you want to display 12.56. This is useful when you are playing with Currency.
The following code snippets can be use to truncate values without rounding.

Method 1: Use Math.trunc(x)

let result = Math.trunc(number*100)/100

We are using 100 because we want to truncate number by 2 decimal points, similarly if you want to truncate number by 3 decimal points you can use the above line as:

let result = Math.trunc(number*1000)/1000

The Complete function in more generic way:

function truncNumber(number, decimal){
    return Math.trunc(number*Math.pow(10, decimal))/Math.pow(10, decimal)
}
// You can use this function like this
console.log(truncNumber(12.66785, 2))
// output will be 12.66

Math.trunc() truncates (cuts off) the dot and the digits to the right of any number. The given number can be positive or negative number.

Method 2: Using regular expression

You can also use the regx to truncate the number like the following:

function truncNumber(num, decimal) {
    var re = new RegExp('^-?\\d+(?:\.\\d{0,' + (decimal|| -1) + '})?');
    return Number(num.toString().match(re)[0]);
}

The above code is using simple regular expression which find the string part with desired decimal points. num.toString().match(re)[0] returns value as string, If you want the value as number you need to convert into number using Number or parseFloat methods.