5

I wnat to get values from input elements as numbers and count them with jQuery. I'm trying, but result is not on decimal. How to fix that problem ?

HTML

<input name="test1" value="1.77" type="hidden" />
<input name="test2" value="1.23" type="hidden" />

jQuery

var a = parseInt($( "input[name='test1']").val(), 10);
var b = parseInt($( "input[name='test2']").val(), 10);
alert( a + b ); // should be 3, but it is only 2

Here is an example -> jsfiddle Example

Patrik
  • 1,159
  • 6
  • 29
  • 47

5 Answers5

7

Use parseFloat for decimals and not parseInt (which is for integers)!

e.g.

var a = parseFloat($( "input[name='test1']").val(), 10);
var b = parseFloat($( "input[name='test2']").val(), 10);
var c = ( a + b );

$('#result').append( c );

JSFiddle: http://jsfiddle.net/TrueBlueAussie/87tdj7z3/5/

Gone Coding
  • 88,305
  • 23
  • 172
  • 188
  • Thank you very much, it solves the problem... I have one another question. What do you think about this error ? http://jsfiddle.net/ynternet/87tdj7z3/7/ – Patrik Nov 27 '14 at 12:35
  • 1
    That's a floating point rounding error. You often need to resort to the math library to round numbers to a specific number of decimal places. – Gone Coding Nov 27 '14 at 13:57
5

the + operator is a shortcut to parse numbers including integer and float.

var a = +$("input[name='test1']").val();
var b = +$("input[name='test2']").val();
alert(a + b);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="test1" value="1.77" type="hidden" />
<input name="test2" value="1.23" type="hidden" />
Neverever
  • 13,862
  • 3
  • 28
  • 47
  • If you wanted to sum these numbers would the syntax be `a += +$("input[name='test1']").val()`? – Martin Feb 01 '21 at 10:44
3

Use parseFloat instead of parseInt as follows

var a = parseFloat($("input[name='test1']").val());
var b = parseFloat($("input[name='test2']").val());
alert( a + b );

fiddle

1
function myFunction() {
    var a = parseFloat("10") + "<br>";
    var b = parseFloat("10.00") + "<br>";
    var c = parseFloat("10.33") + "<br>";
    var d = parseFloat("34 45 66") + "<br>";
    var e = parseFloat("   60   ") + "<br>";
    var f = parseFloat("40 years") + "<br>";
    var g = parseFloat("He was 40") + "<br>";

    var n = a + b + c + d + e + f + g;
    document.getElementById("demo").innerHTML = n;
}
MiDhuN
  • 212
  • 2
  • 10
1

I found I was getting values from inputs via jQuery and calling parseFloat a lot so I created a small jQuery plugin to return an input value as a number, making use of the plus operator:

jQuery.fn.valNum = function () {
    return +(this.val());
};
Matthew
  • 1,182
  • 1
  • 8
  • 16