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

Check if the value is greater than or equal to the nearest lowest 0.05 in JavaScript

I want to check whether a decimal value is greater than or equal to the nearest low 0.05 value

Example

Value | Expected Nearest 0.05 value 
11.10 |    11.05           
11.11 |    11.10           
11.12 |    11.10           
11.13 |    11.10           
11.14 |    11.10           
11.15 |    11.10           

I tried using the formula

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

parseFloat((Math.floor(value * 20) / 20).toFixed(2))

But it fails for 11.10 and 11.15. Using the above formula I get the output same as the value but the expected values are different. Which formula should I use to fix the above test cases.

>Solution :

You could take an offset and take a multiple floored value.

const format = f => Math.floor((f - 0.01) * 20) / 20;

console.log([11.10, 11.11, 11.12, 11.13, 11.14, 11.15, 11.16, 11.17, 11.18, 11.19].map(format));
.as-console-wrapper { max-height: 100% !important; top: 0; }
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