Emrah Özdemir
Emrah Özdemir

Reputation: 35

jquery multiplication with broken numbers

i coded price * Qty function with jquery but not responding daily prices. They response decimal numbers.

Here is code;

 var qty = "3";
 var price = "1.20";
 var res = (qty*price);
 $("#boxres").html(res);

They result 3.5999999999999996

i want to only 3.6 how can i fix it ?

Upvotes: 0

Views: 129

Answers (3)

Chris Rosete
Chris Rosete

Reputation: 1258

try

$("#boxres").html(res.toFixed(1));

http://jsfiddle.net/dfz0bj3z/

Upvotes: 1

TyMayn
TyMayn

Reputation: 1936

Use Math.round

var res = (Math.round((qty*price)*10)/10).toFixed(2);

Edit to force to the 100th. Thanks dave.

Upvotes: 0

Eric
Eric

Reputation: 97591

Store things in pennies:

var qty = 3;
var cost = 120;
var res = cost * qty;
var res_str = '£'+Math.floor(res / 100)+'.'+(res %100).toFixed(2);

Upvotes: 2

Related Questions