I am working on a web application and using javascript to restrict or round off a value. Whenever I enter any decimal value in a textbox, it should be rounded off to .25, .50, .75, or .00. any idea how to do that? Even if am able to enter only .25, .50, .75 and .00 is also fine... but how to restrict for only these specific values?
I am working on a web application and using javascript to restrict or round off a value. Whenever I enter any decimal value in a textbox, it should be rounded off to .25, .50, .75, or .00. any idea how to do that? Even if am able to enter only .25, .50, .75 and .00 is also fine... but how to restrict for only these specific values?
Share Improve this question edited Jul 18, 2012 at 20:50 David Navarre 1,02210 silver badges27 bronze badges asked Jul 18, 2012 at 9:17 AksharAkshar 1111 silver badge11 bronze badges 3- Is this about Java or JavaScript? The two are unrelated. – Blender Commented Jul 18, 2012 at 9:19
- Considering he has added jquery my guess would be JavaScript. – Vala Commented Jul 18, 2012 at 9:19
- I'm interested in seeing if anyone has an elegant solution for this, but you can always extract the decimals and use if's. It's not pretty, but since you have few options it's actually likely to be the most performant. Not maintainable though. – Vala Commented Jul 18, 2012 at 9:22
5 Answers
Reset to default 4Or:
var n = $('#myInput').val();
alert(.25 * Math.round( 4 * n));
The jQuery UI spinner has this functionality built in.
http://btburnett./spinner/example/example.html
OR
http://www.htmldrive/items/demo/541/jQuery-UI-Spinner-numeric-stepper
You just need an if statement
For example, lets assume instead that you were trying to round to the nearest whole number you would do the following or something similar:
var remainder = value - Math.floor(value);
if(remainder < 0.5)
newValue = Math.floor(value);
else
newValue = Math.floor(value) + 1;
There however are many many ways of doing this, you just need to pick the appropriate numbers instead of 0.5 and may need to check several ranges.
I am in no way saying this is the best option but this should give you an idea.
As for the textbox entry you can run this every keyup/keydown etc and replace the value with your newValue
In case it's not obvious from Jon Taylors answer, the appropriate way of using if statements to solve this is the following:
var floorValue = Math.floor(value);
var remainder = value - floorValue;
if (remainder < 0.325) {
if (remainder < 0.125) {
newValue = floorValue;
} else {
newValue = floorValue + 0.25;
}
} else {
if (remainder < 0.625) {
newValue = floorValue + 0.5;
} else if (remainder < 0.875) {
newValue = floorValue + 0.75;
} else {
newValue = floorValue + 1;
}
}
var decimal = n - Math.floor(n)
decimal=decimal*100;
var factor = Math.round(decimal/25)
decimal = n + 0.25*factor;