How to get value from input element as a number in decimal
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)!
eg
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/
+
运算符是解析数字(包括整数和浮点数)的快捷方式。
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
链接地址: http://www.djcxy.com/p/73942.html上一篇: 在Java中使用= +运算符?
下一篇: 如何从输入元素中获取值作为十进制数字