Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

parse decimale toFixed(2) on decimals which are not 0

The aim is to have 2 decimals without counting 0

1.2234 => 1.22

0.2345 => 0.23

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

0.02345 => 0.023 (instead of 0.02)

0.0000002345 => 0.00000023 (instead of 0)

0.0000002346545645645646465465 => 0.00000023 (instead of 0)

0.002035 => 0.002 instead of 0)

I want to parse toFixed(2) but on the decimals which are not 0. How to do this properly ?

>Solution :

I think from example what you meant remove last 2 digits instead of making it fixed into 2 decimals.

To do so, heres my approach.

 function removeLastDigit(number, amount = 2)
{
  const numberString = number.toString();
  if(numberString.indexOf('.') === -1) return number;
  let numberLength = numberString.length;
  for(; numberLength >= 0 && amount; numberLength--){
    if (numberString[numberLength] !== '0') amount--;
  }
  return +numberString.slice(0, numberLength);
}
let num = 0.003040;
console.log(removeLastDigit(num)) //0.03

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading