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
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/
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" />
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
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With