Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

I currently have a simple numpad that's setup to insert a dollar amount into the span tag .bill-amount__integer. The default text within this span reads as 0.00.

<div class="bill-amount__value">
    <span>$</span><span class="bill-amount__integer">0.00</span>
</div>

Right now the numeric digits of each button is appended to the span in a stack-like fashion LIFO which is seen in the first and last blocks of the conditional below.

$(".numpad__button").on("click", function() {
    var that = this,
        $that = $(that);

    if ($that.hasClass("numpad__button--backspace")) {
        $(".bill-amount__integer").text(function(index, value) {
            return value.slice(0, -1);
        });
    } else if ($that.hasClass("numpad__button--return")) {
        if ($(".bill-amount__integer").text().length === 0) {
            $(".bill-amount__value").hide(0, function() {
                $(this).prev().show()
            });
        }
        $(".numpad").removeClass("numpad--raised");
    } else {
        $(".bill-amount__integer").text(function(index, value) {
            return value += that.innerText;
        });
    }
});

What I'd like to do is replace the 0 and insert the selected integer starting from the right and working its way to the left. So for instance:

0.05  // If I insert the number 5
0.50  // If I insert numbers 5 and 0
5.50  // If I insert numbers 5,0,0 
50.50 // If I insert numbers 5,0,0,0

The same methodology would work for removing numbers but re-inserting 0 in its place (reversed).

50.50 // Starts out at 50.50 and is reduced in the sequence below
5.05
0.50
0.05

I addition to inserting/removing integers I also wanted to add a comma for every three digits. I managed to do this using the regex below but didn't exactly how to integrate it with what I'm looking to achieve:

$(".numpad__button").on("click", function() {
  ...
  $(".bill-amount__integer").text(function(i, v) {
    return v.replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  });
});

JSFiddle

share|improve this question
    
This isn't a full answer--it's just to get you started--so I'll post it as a comment. All I did was change that final return statement in your number pad click handler. http://jsfiddle.net/3o94pf5h/11/ – thewatcheruatu May 18 '15 at 14:27
    
The fiddle looks great. I know you said that this is something to get started but you wouldn't know what's causing the replace method inside the text method to remove the . and stop at 4 digits? To see what I'm talking about uncomment the code in the click event. – Carl Edwards May 18 '15 at 14:36
    
Well, yeah, it's because parseFloat doesn't work if there are commas in the string. You can try something like this. jsfiddle.net/3o94pf5h/12 Just to be clear, I'm not saying this is necessarily the best way to do it. Other answers might give you better choices. I just worked with what you had. – thewatcheruatu May 18 '15 at 14:55
    
Right on and many thanks for your suggestions nonetheless. Would your most recent changes also work in a similar manner for removing/replacing digits when you click the backspace button? Right now the code for that particular button slices the last digit out-right but I'm wondering if there was a way to replace that digit with a 0. – Carl Edwards May 18 '15 at 15:00
2  
Here is where it starts to get messy (well, messier). I would definitely recommend a different way of storing your value, for example, rather than parsing it from the formatted string every time. – thewatcheruatu May 18 '15 at 15:15
up vote 2 down vote accepted

There's something I don't really get, why so much pain slicing and constructing strings, when all you have to do is divide the entered number by 100?

Is this what you want? (Not sure)

$span = $("span");
$("input").on('keyup change', function(){
    $span.text(($(this).val()/100).toFixed(2) || '0.00')
})
                  
             
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number">
<p>Result : <span>0.00<span></p>

About number formatting, have a look at jQuery-numberFormatter.

Edit

Okay, I rewrote your code, I think it's working now : http://jsfiddle.net/3o94pf5h/16/

share|improve this answer
    
This looks good but I'm still unsure on the regex used to insert the commas. Is writing a regex even needed or is there a better way to handle this? – Carl Edwards May 18 '15 at 14:38
    
I think you missed the last line of my answer ;) – Jeremy Thille May 18 '15 at 14:44
    
I did indeed thanks. I tried translating your code to what I have now but it seems that it only changes the first digit to the right: jsfiddle.net/TKB21/3o94pf5h/13 – Carl Edwards May 18 '15 at 14:54
    
Okay, I rewrote your code and I believe it works now : jsfiddle.net/3o94pf5h/16 I'm using a "total" variable that stores the amount, instead of reading what's written in the span every time a key is pressed. – Jeremy Thille May 18 '15 at 15:17
    
Thanks so much for suggesting this method. Also +1 for taking the time out to refactor the code. I'll experiment with jQuery-numberFormatter to get those commas inserted as well. You wouldn't happen to know if it works on elements other than inputs? Anyways thanks again and I really appreciate your help! – Carl Edwards May 18 '15 at 15:31

To manipulate the value, just multiple by 10 or 100; or divide by 10 or 100. You need only to pad the numbers with zeros and add commas. It sounds like the "cash register" type of buttons, there is a "0" and a "00", that automatically made a [5][00] = $5.00, and a [5][0][00] = $50.00, etc.. ???

Use javascript's toFixed method. Example:

var number = 425.1;    
var formatted = number.toFixed(2); // formatted = 425.10

There are some pre-built-jQuery code: jquery.formatNumber

//produces 29,323,894.23 (e.g. US standard)
$('.number').formatNumber({
  cents: '.',
  decimal: ','
});

More pre-built-jQUery code: jquerypriceformat.com

$('#htmlfield').priceFormat();
Result:  US$ 1,234.56

$('#example2').priceFormat({
    prefix: 'R$ ',
    centsSeparator: ',',
    thousandsSeparator: '.'
});
Result:  R$ 1.234,56

Adding commas, borrowed from: Number formatting, add commas

function addCommas(nStr) {
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.