2

I have a text input for a money field.

I enter 33.91 into the field, and get the following results while trying to use the 'multiply by 100' technique.

var curWth = parseInt($('#trans_withdraw'+index).val()*100);   // 3390
var curWth = parseInt($('#trans_withdraw'+index).val())*100;   // 3300  
var curWth = $('#trans_withdraw'+index).val()*100;             // 3390.9999999...5
var curWth = parseFloat($('#trans_withdraw'+index).val())*100; // 3390.9999999...5
var curWth = parseFloat($('#trans_withdraw'+index).val()*100); // 3390.9999999...5

None of these give me 3391. I thought the whole idea of multiplying by 100 was to get away from the floating point problem. But as line 3 shows, when I multiply the value by 100 immediately, I still get floating point errors.

What am I still not understanding about working with currency?

I know 0.1 can't be stored correctly as a float. But multiplying by 100 is also not working for me in this case.

Nertskull
  • 491
  • 6
  • 20

1 Answers1

2
praseFloat to get your decimal value then multiple by 100 to get 3390.9999 then Math.round() to get the value.

var number = parseFloat($('#trans_withdraw').val()).toFixed(2);
var value = number * 100;

console.log(Math.round(value));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="trans_withdraw" value="33.91" />
Monkey_Dev1400
  • 924
  • 6
  • 14