Nirav Ghodadra
Nirav Ghodadra

Reputation: 352

Truncate a number

function truncDigits(inputNumber, digits) {
const fact = 10 ** digits;
return Math.trunc(inputNumber * fact) / fact;
}
truncDigits(27624.399999999998,2) //27624.4 but I want 27624.39

I need to truncate a float value but don't wanna round it off. For example 27624.399999999998 // 27624.39 expected result

Also Math.trunc gives the integer part right but when you Math.trunc value 2762439.99 it does not give the integer part but gives the round off value i.e 2762434

Upvotes: 0

Views: 117

Answers (3)

Radu Diță
Radu Diță

Reputation: 14171

You can try to convert to a string and then use a RegExp to extract the required decimals

function truncDigits(inputNumber: number, digits: number) {
 const match = inputNumber.toString().match(new RegExp(`^\\d+\\.[\\d]{0,${digits}}`))

 if (!match) {
   return inputNumber
 }

 return parseFloat(match[0])
}

Note: I'm using the string version of the RegExp ctor as the literal one doesn't allow for dynamic params.

Upvotes: 0

Stefano Leone
Stefano Leone

Reputation: 703

Try this:

function truncDigits(inputNumber, digits){  
   return parseFloat((inputNumber).toFixed(digits));
}
truncDigits(27624.399999999998,2)

Your inputs are number (if you are using typescript). The method toFixed(n) truncates your number in a maximum of n digits after the decimal point and returns it as a string. Then you convert this with parseFloat and you have your number.

Upvotes: 0

Bravo
Bravo

Reputation: 6264

Probably a naive way to do it:

function truncDigits(inputNumber, digits) {
  return +inputNumber.toString().split('.').map((v,i) => i ? v.slice(0, digits) : v).join('.');
}
console.log(truncDigits(27624.399999999998,2))

At least it does what you asked though

Upvotes: 1

Related Questions