Integer in javascript?

I get 28.6813276578 when I multiply 2 numbers a and b, how can I make it an integer with fewer digits

and also, when I multiply again, I get results after the first repetition, for example, 28.681321405.4428.68 how to get only one result?

<script> $(document).ready(function(){ $("#total").hide(); $("#form1").submit(function(){ var a = parseFloat($("#user_price").val()); var b = parseFloat($("#selling").val()); var total = a*b; $("#total").append(total) .show('slow') .css({"background":"yellow","font-size":50}) ; return false; }); }); </script> 
+7
source share
3 answers

You can do a few things:

 total = total.toFixed([number of decimals]); total = Math.round(total); total = parseInt(total); 
  • toFixed() will round your number to the specified number of decimal places.

  • Math.round() will round numbers to the nearest integer.

  • parseInt() will take a string and try to parse an integer from it without rounding. parseInt() bit more complicated because it will parse the first characters in the string, which are numbers until they are, i.e. parseInt('123g32ksj') will return 123 , while parseInt('sdjgg123') will return NaN .

    • For completeness, parseInt() takes a second parameter that you can use to express the base you are trying to extract, which means, for example, parseInt('A', 16) === 10 if you tried to parse a hexadecimal number.
+23
source

In addition to the other rounding answers, you add the answer to "total" using

 $("#total").append(total) 

You need to replace the previous text, not add using

 $("#total").html(total) 
+2
source
+1
source

All Articles