0

So I have a number var test_price = 94600. I want to multiply it by the value a user types in an <input name="quantity" /> element, and to show that result in a <p id="sample"> element. This is self-describing: in the <p> element it shows the total price (price * quantity). I've managed to do that:

$('input[name="quantity"]').change(function () {
    var test_price = 94600;
    var quantity = $('input[name="quantity"]').val();
    var price_without_thousands_separator = $('#sample').html(test_price * quantity);
});

As you can see it's working.

Now I just want to add a period (.) after every three units to the #sample paragraph. So if you have 1 as quantity it will show 94.600, if you have quantity=3 then 283.800, if quantity=8 then 756.800 and so on. Yes I know the usual tradition is to use commas, but here in my country we're used to read periods as thousands separators and commas as decimals (e.g. for us π = 3.14, not 3,14).

Happy holidays!!

alejnavab
  • 1,136
  • 1
  • 12
  • 30
  • The above is a duplicate in that all you have to do is switch `","` to `"."` in the code it gives. – 4castle Dec 23 '16 at 22:56
  • How can I insert his code (`function numberWithCommas(x) {return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");}`) into mine? I don't undestand that – alejnavab Dec 23 '16 at 23:05
  • 1
    You have to add this function and call it when setting the html var price_without_thousands_separator = $('#sample').html(numberWithCommas(test_price * quantity)); – bormat Dec 23 '16 at 23:19
  • Hey @bormat thank you a lot! There're some things I still don't understand very well such as parameters/arguments in JS. If any body wants to test the new code, **[here it is](https://jsfiddle.net/0wg7y6x9/4/)**. – alejnavab Dec 24 '16 at 05:38

1 Answers1

0

here is a very simple solution for up to 6 digits.

var x = test_price * quantity;
x = x.toString();
var withComma = x.slice(0, x.length - 3) + ',' + x.slice(-3);

to make this more robust, you may want to make a formatInt() function that loops through your string and at every 3rd digit from the end adds the comma

s_cicero
  • 155
  • 11
  • How would I use that `formatInt()`? [You can see you solution worked](http://jsfiddle.net/0wg7y6x9/3), but once the value of input is greater than or equal to 11, the number is displayed 1040.600 instead of 1.400.600. – alejnavab Dec 23 '16 at 23:41
  • 1
    I'd go with this regex solution. http://stackoverflow.com/a/2901298/3465999 so in your case, add that function and call numberWithCommas(test_price * quantity). Also, replace the ',' with '.' – s_cicero Dec 24 '16 at 00:04