How to use division in JavaScript


Javascript Problem Overview

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?

Javascript Solutions

Solution 1 - Javascript

Make one of those numbers a float.


or a bit faster:


convert to 2 decimal places

Math.round(737 * 100.0 / 1070) / 100

Solution 2 - Javascript

(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

Solution 3 - Javascript

Also you can to use [.toPrecision(n)], where n is (total) the number of digits. So (23.467543).toPrecision(4) => 23.47 or (1241876.2341).toPrecision(8) => 1241876.2.


Solution 4 - Javascript

Try this

 let ans = 737/1070;

toFixed() function will do

Solution 5 - Javascript

to get it to 2 decimal places you can: alert( Math.round( 737 / 1070 * 100) / 100 )

Solution 6 - Javascript

with lodash:

const _ = require("lodash"); 

Use of _.divide() method

let gfg = _.divide(12, 5);


Printing the output




All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDayzzaView Question on Stackoverflow
Solution 1 - JavascriptCharles MaView Answer on Stackoverflow
Solution 2 - JavascriptKooiIncView Answer on Stackoverflow
Solution 3 - JavascriptVladimirView Answer on Stackoverflow
Solution 4 - JavascriptelraphtyView Answer on Stackoverflow
Solution 5 - JavascriptBilly MoonView Answer on Stackoverflow
Solution 6 - JavascriptEmbedded_MugsView Answer on Stackoverflow