jquery-maskmoney: Wrong masked values without decimal

Hey guys… When I’m editing some fields and I have my input rendered as follow:

<input type="text" class="mask-money"  value="10000" data-thousands="." data-decimal="," data-prefix="R$ ">
<input type="text" class="mask-money" value="4500" data-thousands="." data-decimal="," data-prefix="R$ ">

<input type="text" class="mask-money"  value="1" data-thousands="." data-decimal="," data-prefix="R$ ">
<input type="text" class="mask-money"  value="1.1" data-thousands="." data-decimal="," data-prefix="R$ ">

<input type="text" class="mask-money"  value="0.8" data-thousands="." data-decimal="," data-prefix="R$ ">
<input type="text" class="mask-money"  value="0.88" data-thousands="." data-decimal="," data-prefix="R$ ">

First, feels weird to have to do this in order to mask the fields:

$('.mask-money').maskMoney(); // shouldn't this be enough?
$('.mask-money').maskMoney('mask'); // is this really necessary?

But the problem is that I get this values:

  • 100,00 (instead of 10.000,00)
  • 45,00 (instead of 4.500,00)
  • 0,01 (instead of 1,00)
  • 0,11 (instead of 1,10)
  • 0,08 (instead of 0,80)
  • 0,88 (yeah! fot his one right)

About this issue

  • Original URL
  • State: open
  • Created 10 years ago
  • Comments: 17 (3 by maintainers)

Most upvoted comments

We ran into this issue as well. As a work around I am using javascripts Number() to convert the value to a number during the mask. Below is an example:

http://jsfiddle.net/5pgdq8od/1/

see pull request with possible fix: https://github.com/plentz/jquery-maskmoney/commit/2de7b9a5f09d44731fcd0ef9c0c751eeb24e48b1

jsfiddle with some tests for fix: http://jsfiddle.net/6vyL2v7f/

I’ve read everything but I had to solve my problem RIGHT NOW. So here goes an UGLY patch. My values that should show R$ 500,00 were showing as R$ 50,00.

It makes the value of the field get two decimals when it has only one, so 500.0 becomes 500.00, 100.1 becomes 100.10. I do it right before setting the maskMoney on the field, and it fixed it for now (for me)

Be very careful with this patch. I will remove it as soon as the rails gem I’m using for this lib is correct.

function setupMoneyFields(){
   var moneyFields = $("input.money");

   // Iterating so I can have multiple money fields on the same page.
   $.each(moneyFields, function(){
      replaceSingleDecimalByDouble($(this));
   });

   moneyFields.maskMoney({
     thousands: '.',
     decimal: ',',
     prefix: "R$ ",
     allowZero: true
   });
   moneyFields.maskMoney('mask');
}

// Doing this because of Jquery MaskMoney's issue, that is turning 500.0 into R$ 50,00
function replaceSingleDecimalByDouble(jquerySelector){
  var currentValue = jquerySelector.val();
  jquerySelector.val(currentValue.replace(/\.(\d)\b/, ".$10"));
}

I hope that helps someone somehow, and here goes my +1 for fixing this.