Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

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.

like image 502
sheetaldharerao Avatar asked Nov 02 '25 01:11

sheetaldharerao


2 Answers

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; }
like image 105
Nina Scholz Avatar answered Nov 03 '25 17:11

Nina Scholz


You can multiply the values by 100 to temporarily remove the needed two decimal points, the nearest number now becomes a multiple of 5, you can then remove the rest of the Euclidean division by 5 and get what you want.

And since an exact multiple of 5 needs to be brought to the nearest lower value, you can conditionally remove a 5 when the rest is equal to 0.

The formule function could be something like:

const f = (v) => (((Math.floor(v*100) - (Math.floor(v*100) % 5 || 5)) / 100).toFixed(2));
console.log('11.10', f(11.10));
console.log('11.11', f(11.11));
console.log('11.12', f(11.12));
console.log('11.13', f(11.13));
console.log('11.14', f(11.14));
console.log('11.15', f(11.15));
like image 33
Ghassen Louhaichi Avatar answered Nov 03 '25 15:11

Ghassen Louhaichi



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!