views:

40

answers:

3

Hi guys,

as the title states, I am trying to add two floats using javascript/jquery, and then assign the value to another input field, but sometimes when I add the two I get something like 1234.567800000000, any idea on how I can fix this?

EDIT: I would like something like this, 1234.56

here is my code,

jQuery:

$("[data-custom*='min_sys'], [data-custom*='min_inst'], [data-custom*='max_sys'], [data-custom*='max_inst']").live('keyup',function(){
 //the parent
 var parent = $(this).closest('[class*="costing"]');

 var one = Number(parent.find('[data-custom*="max_sys"]').val());
 var two = Number(parent.find('[data-custom*="max_inst"]').val());
 var sum = one+two;

        //here I set the value of the 'total_inst input' box to the variable 'sum'
 var total = parseFloat(parent.find('[data-custom*="total_inst"]').val(sum));

});

Also, what would be the best way to store a float like that (the total) in a database, what data type would be the best?

Thanx in advance!

A: 

You could round it with Math.round().

alex
+1  A: 

Since you are adding floating point numbers, it is possible that you have a long list of decimal places.

You may need to truncate/round off your results.

See Math.round, Math.floor etc in the javascript Math object

Nivas
+4  A: 

Since you're putting the results into an input field, you could use the toFixed() method. It takes an argument that is the number of decimal places you wish to see, and outputs a string. For example:

var n = 345.2020110000

n.toFixed(3) // 345.202
n.toFixed(5) // 345.20201
Robusto
Thanx, that worked a treat!