0

say i have the following number 2,74.

If you divide this number by 4, the result is 0.685.

I want to divide this number by 4 but the result should be rounded to 2 decimals. So my result should be:

3 times 0.69 and a remainder of 0.67

Does anyone have a clue how to do that in javascript? I have absolutely no idea how i should tackle this.

vincent
  • 1,243
  • 4
  • 15
  • 29

3 Answers3

1

Here's a way you could do this :

var n = 2.74
var x = (n / 4).toFixed(2)
// renders string "0.69"
var r = (n - 3 * parseFloat(x, 10)).toFixed(2)
// renders string "0.67"

Explanation :

  • method (n).toFixed(x) takes the number n with its x first digits, and returns a string

  • method parseFloat(s, b) takes a string s and returns a floating point number in base b

John Pink
  • 607
  • 5
  • 14
  • Nice and easy +1. I would advise against using toFixed and going for the method rossipedia provided – ThomasS Oct 28 '15 at 16:08
  • May I ask what you dislike about the `toFixed` method ? – John Pink Oct 28 '15 at 16:11
  • it has some problems with rounding for certain numbers. This is due to how floating point numbers work. This http://stackoverflow.com/questions/10015027/javascript-tofixed-not-rounding for example explains it – ThomasS Oct 29 '15 at 13:02
0

Since you're looking for 2 digits of precision, you want to multiply the number by 10^2 (100) and then round to the nearest integer by calling Math.round. Then divide the result by the same factor you multiplied by (100).

If you want more digits of precision (after the decimal point), then just multiply/divide by larger powers of 10 (eg: 3 digits would be 1000, 4 would be 10000, etc).

var n = 2.74;
var result = Math.round((n / 4) * 100) / 100;

document.getElementById('output').innerHTML = (result * 3).toString() + '<br>' + (n - (result*3));
<div id="output"></div>

Another option as mentioned in the comments to your question would be to use toFixed:

var n = 2.74;
var result = (n/4).toFixed(2) * 3;
rossipedia
  • 56,800
  • 10
  • 90
  • 93
0

Solution with test if remainder is necessary.

function getParts(num, parts, precision) {
    var v = +(num / parts).toFixed(precision),
        r = +(num - v * (parts - 1)).toFixed(precision);
    return v === r ? { parts: parts, value: v } : { parts: parts - 1, value: v, remainder: r };
}
document.write('<pre>' + JSON.stringify(getParts(2.74, 4, 2), 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(getParts(3, 4, 2), 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(getParts(4, 3, 2), 0, 4) + '</pre>');
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392