JavaScript only has one numeric type and it's a 64-bit floting point number. You'll have to deal with lack of precision. parseFloat takes a string and returns a number.
var Valor = "";
Valor = $("#txtValor").val();
if (Valor && Valor != "" && Valor != null && Valor != "undefined") {
Valor = Valor.replace(',', '.');
}
else {
Valor = "0";
}
alvaro_web
Member
121 Points
172 Posts
Subtraction operation in javascript
Feb 24, 2013 10:53 PM|LINK
Using VS2010, aspnet, c#, javascript
subtraction operation in javascript
value = 99.99;
discount = 0.01;
var total = "";
total = (parseFloat (value) - parseFloat (discount));
displayed result = 99.97999999999999
-----javascript------
var a = 99.99 + 0.02;
alert(a);
alert = 100.00999999999999
-----------------------
resultaddo correct = 99.98
I'm doing it wrong?
BrockAllen
All-Star
27434 Points
4891 Posts
MVP
Re: Subtraction operation in javascript
Feb 24, 2013 10:59 PM|LINK
JavaScript only has one numeric type and it's a 64-bit floting point number. You'll have to deal with lack of precision. parseFloat takes a string and returns a number.
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Number
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/parseFloat
DevelopMentor | http://www.develop.com
thinktecture | http://www.thinktecture.com/
alvaro_web
Member
121 Points
172 Posts
Re: Subtraction operation in javascript
Feb 24, 2013 11:15 PM|LINK
BrockAllen
function Soma() {
var Valor = "";
Valor = $("#txtValor").val();
if (Valor && Valor != "" && Valor != null && Valor != "undefined") {
Valor = Valor.replace(',', '.');
}
else {
Valor = "0";
}
var Desconto = "";
Desconto = $("#txtDesconto").val();
if (Desconto && Desconto != "" && Desconto != null && Desconto != "undefined") {
Desconto = Desconto.replace(',', '.');
}
else {
Desconto = "0";
}
var soma = "";
soma = ((parseFloat(Valor) - parseFloat(Desconto);
if (soma > 0) {
var resultado = "";
resultado = soma.toString();
resultado = resultado.replace('.', ',');
$("#txtTotal").empty;
$("#txtTotal").val(resultado);
}
}
but the error continues: 99.99 - 0.01 = 99.97999999999999
Yanping Wang...
Star
14859 Points
1525 Posts
Microsoft
Re: Subtraction operation in javascript
Feb 26, 2013 05:21 AM|LINK
Hi alvaro_web,
you can use toFixed(2) method to keep only 2 decimal, eg.
soma = (parseFloat(Valor) - parseFloat(Desconto).toFixed(2);
more details about toFixed() function please refer http://www.w3schools.com/jsref/jsref_tofixed.asp
hope this helps, thnaks.
Feedback to us
Develop and promote your apps in Windows Store