Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use division in JavaScript

I want to divide a number in JavaScript and it would return a decimal value.

For example: 737/1070 - I want JavaScript to return 0.68; however it keeps rounding it off and return it as 0.

How do I set it to return me either two decimals place or the full results?

like image 750
Dayzza Avatar asked Sep 07 '11 09:09

Dayzza


People also ask

How do you int divide in JavaScript?

In JavaScript, we can get the quotient and remainder of a division using the bitwise operators. For example, we can get the quotient of a division using the bitwise NOT ~~ or bitwise OR |0 , which converts the floating-point number to an integer. And to get the remainder, we can use the % character.

Can you divide by a string in JavaScript?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.


2 Answers

Make one of those numbers a float.

737/parseFloat(1070) 

or a bit faster:

737*1.0/1070 

convert to 2 decimal places

Math.round(737 * 100.0 / 1070) / 100 
like image 139
Charles Ma Avatar answered Sep 28 '22 11:09

Charles Ma


(737/1070).toFixed(2); rounds the result to 2 decimals and returns it as a string. In this case the rounded result is 0.69 by the way, not 0.68. If you need a real float rounded to 2 decimals from your division, use parseFloat((737/1070).toFixed(2))

See also

like image 43
KooiInc Avatar answered Sep 28 '22 13:09

KooiInc