Reputation: 1327
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
Upvotes: 5
Views: 23224
Reputation: 1797
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());
};
Upvotes: 1
Reputation: 16440
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" />
Upvotes: 5
Reputation: 33
Use parseFloat instead of parseInt as follows
var a = parseFloat($("input[name='test1']").val());
var b = parseFloat($("input[name='test2']").val());
alert( a + b );
Upvotes: 3
Reputation: 232
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;
}
Upvotes: 1
Reputation: 93571
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/
Upvotes: 7