Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round down decimals javascript

I am working on a JS project and i have the following problem:

My input number goes from 0 to 10. (it can be 1, 2, 3.4, 5,9, etc..)

The expected output would be something out of 5 with only one lowered down decimal.

Examples:

9.7 / 10 would give 4.85 / 5 , the output has to be 4.8 (keep only one lowered down digit)

4.9 / 10 would give 2.45 / 5, the output has to be 2.4 (keep only one lowered down digit)

Thanks for your help.

Regards


1 Answers

You can do this with a simple process:

  1. Multiply your number by 10.
  2. Floor it (using Math.floor).
  3. Divide it by 10.
Math.floor(4.85 * 10) / 10; // 4.8
Math.floor(2.45 * 10) / 10; // 2.4
Math.floor(3 * 10) / 10;    // 3

Taking 4.85 as an example:

  1. 4.85 * 10 equates to 48.5.
  2. Math.floor(48.5) equates to 48.
  3. 48 / 10 equates to 4.8.
like image 55
James Donnelly Avatar answered Jul 02 '26 05:07

James Donnelly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!