Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

whole number in javascript?

I get 28.6813276578 when i multiply 2 numbers a and b, how can i make it whole number with less digits

and also, when i multiply again i get results after first reult like 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>
like image 323
ktm Avatar asked Apr 28 '11 07:04

ktm


People also ask

How do you make a whole number in JavaScript?

Use the Math. round() function to round the result to the nearest integer.

How do you round to whole numbers in JavaScript?

The Math. ceil() method rounds a number rounded UP to the nearest integer.

What is whole number format?

There is no fractional or decimal part. And no negatives. Example: 5, 49 and 980 are all whole numbers.


2 Answers

You can do several things:

total = total.toFixed([number of decimals]);
total = Math.round(total);
total = parseInt(total);
  1. toFixed() will round your number to the number of decimals indicated.

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

  3. parseInt() will take a string and attempt to parse an integer from it without rounding. parseInt() is a little trickier though, in that it will parse the first characters in a string that are numbers until they are not, meaning parseInt('123g32ksj') will return 123, whereas parseInt('sdjgg123') will return NaN.

    • For the sake of completeness, parseInt() accepts a second parameter which can be used to express the base you're trying to extract with, meaning that, for instance,
      parseInt('A', 16) === 10 if you were trying to parse a hexidecimal.
like image 134
Jason Avatar answered Sep 29 '22 12:09

Jason


See Math.round(...).

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Math/round

like image 22
DuckMaestro Avatar answered Sep 29 '22 11:09

DuckMaestro