ATM style decimal places

2019-05-10 03:20发布

问题:

I'm working on getting an old piece of code working, from 2003. I'm trying to replicate an ATM style decimal textbox. This code claims to have worked for someone, but I am having trouble implementing it.

Maybe someone has a better way of achieving this? Maybe in jQuery?

回答1:

This is how I would solve it: http://jsfiddle.net/77bMx/86/

  • Handles numpad input as well as standard number keys
  • Works with backspace
  • Will revert to 0.00 if you somehow manage to produce illegal input (like backspacing too much)

The basic idea is to intercept any input to the box, make sure it's of the correct type (a number, or a backspace) and then add it to a backing storage string (var input), and then format that string to display correctly. The user never directly enters anything into the text box, since I use return false at the end of the event handler.



回答2:

Well, the code for processing the input can easily be made like this:

$("#number").keyup(function(e){
    var number = $("#number").val();
    var newValue = (Math.round(parseFloat(number)*100)/100)/100;
});

It might be a challenge getting it back into the textbox without getting conflicts, but you could 'fake' it by doing something like this:

http://jsfiddle.net/AnfCn/1/

Disclaimer: Quick and dirty