Home > database >  Truncate a number
Truncate a number

Time:07-03

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

CodePudding user response:

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

CodePudding user response:

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.

CodePudding user response:

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.

  • Related