Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 232
Patrik Avatar asked Nov 27 '14 12:11

Patrik


4 Answers

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/

like image 139
Gone Coding Avatar answered Sep 19 '22 15:09

Gone Coding


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" />
like image 36
Neverever Avatar answered Sep 19 '22 15:09

Neverever


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

like image 33
Muya George Avatar answered Sep 18 '22 15:09

Muya George


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;
}
like image 22
MiDhuN Avatar answered Sep 22 '22 15:09

MiDhuN