jsmreese / moment-duration-format

Format function plugin for the Moment Duration object.
MIT License
968 stars 120 forks source link

Format errors due to floating point issues in Moment.js #94

Closed jsmreese closed 6 years ago

jsmreese commented 6 years ago
moment.duration(123.55, "hours").subtract(5, "days").asHours();
// 3.549999999999997

moment.duration(123.55, "hours").format("d[d] h[h]", 1)
// "5d 3.6h"

moment.duration(123.55, "hours").format("d[d] h[h]", 1, { forceFormatFallback: true })
// "5d 3.5h"

Resulting problem:

(3.549999999999997).toLocaleString("en", {
    minimumFractionDigits: 1,
    maximumFractionDigits: 1
});
// "3.6"

(3.549999999999997).toFixed(1);
// "3.5"

And the actual problem is because:

123.55 - 120;
// 3.549999999999997