0

I have table like this:

enter image description here

The total of the Percentage column must be 100%, but I'm getting 100.01%.

Here's my code:

var hourSlow = $("#input-me-slow").val();
var slowTime = moment.duration(hourSlow).asHours();
// slow time return 2.1666666666666665

var hourIdle = $("#input-me-idle").val();
var idleTime = moment.duration(hourIdle).asHours()
// idle time return 1

var hourEco = $("#input-me-eco").val();
var ecoTime = moment.duration(hourEco).asHours();
// ecoTime return 20.166666666666668

var hourSpeed = $("#input-me-speed").val();
var speedTime = moment.duration(hourSpeed).asHours();
// speedTime return 0.6666666666666666

var fTime = "24:00"
var dfTime = moment.duration(fTime).asHours();
// dfTime return 24

var totalTime = dfTime-speedTime-ecoTime-slowTime-idleTime;
// totalTime return -2.220446049250313e-15


// Here for display it to table, the problem is here
var fPercent = toHour(fullTime); //return 2.78
var ePercent = toHour(ecoTime); //return 84.03
var sPercent = toHour(slowTime); //return 9.03
var iPercent = toHour(idleTime); //return 4.17
$("#me_fullpercen").text(addCommas(fPercent));
$("#me_ecopercen").text(addCommas(ePercent));
$("#me_slowpercen").text(addCommas(sPercent));
$("#me_idlepercen").text(addCommas(iPercent));

// here the function of toHour (I dont know maybe the problem is here)
function toHour(num) {
    var result = (num / 24) * 100;
    return result ;
}

I would rather not round the percentage to 100%, as that would be less precise.

How can I make my percentage 100% instead of 100.01%?

Travis Heeter
  • 13,002
  • 13
  • 87
  • 129
redburn
  • 17
  • 7

1 Answers1

0

This is a common problem, and no matter how precise you try to be, the computer will need to round numbers with repeating decimals at some point. Here's some posts that deal with it:

In those posts you can read about many complex ways to get very close to 100%, but basically there is no right way to do this - when it's all boiled down it's still going to be an estimate - not exactly precise because we're dealing with not-precise numbers. That's just the nature of the beast.

Your program is going to round numbers the wrong way because it's a computer, and it's not intelligent.

Depending on your application, you may want to invest time into reading how to do those complex methods, and maybe you'll get really close.

Add a Footnote

Any path you choose, you'll probably end up putting a footnote explaining this problem anyway. Something like this:

*Because of rounding, these values may not add up to 100%.

Travis Heeter
  • 13,002
  • 13
  • 87
  • 129
  • thanks for replying me. Yes I already read that, and I think, I'll implement some idea which is; if decimal after commas lower than .05 maybe I'll rounded down. for example: 10.396, I'l rounded down to 10.38.. – redburn Oct 19 '18 at 02:31