-1

I try to get a decimal value for further calculation in jquery.

        var vatPercentageString = $("#Price").val();
        var percentage = parseFloat(vatPercentageString).toFixed(2);

But even if I have the value "12,34" in the "Price" textbox I only get 12 as the percentage value, why is that?

MTplus
  • 2,077
  • 4
  • 34
  • 51

2 Answers2

-1

parseFloat doesn't understand commas (,), per the spec:

If parseFloat encounters a character other than a plus sign (+), minus sign (- U+002D HYPHEN-MINUS), numeral (09), decimal point (.), or exponent (e or E), it returns the value up to that character, ignoring the invalid character and characters following it.

So you'll need to replace any commas with decimal points if you'd like to parse them as a number.

// After getting our value, replace `,` with `.`
var vatPercentageString = $("#Price").val().replace(',', '.');
var percentage = parseFloat(vatPercentageString).toFixed(2);
console.log(percentage);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>Price: <input id="Price" value="12,34"></label>
romellem
  • 5,792
  • 1
  • 32
  • 64
-1

Because , is not proper symbol for decimals separator. You should first replace it by .:

function changed() {

  var vatPercentageString = $("#Price").val().replace(',', '.');
  var percentage = parseFloat(vatPercentageString).toFixed(2);

  console.log(percentage);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<input type="text" id="Price" onchange="changed()" />
Justinas
  • 41,402
  • 5
  • 66
  • 96