Reputation: 1557
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?
Upvotes: 67
Views: 118845
Reputation: 2406
with lodash:
const _ = require("lodash");
Use of _.divide() method
let gfg = _.divide(12, 5);
Printing the output
console.log(gfg)
2.4
Upvotes: 0
Reputation: 122888
(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))
Upvotes: 23
Reputation: 31
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
.
Upvotes: 3
Reputation: 630
Try this
let ans = 737/1070;
console.log(ans.toFixed(2));
toFixed() function will do
Upvotes: 2
Reputation: 49141
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
Upvotes: 85
Reputation: 58521
to get it to 2 decimal places you can: alert( Math.round( 737 / 1070 * 100) / 100 )
Upvotes: 0