I'm working on an old Angularjs app, and I need to be able to convert numbers in decimal format to fractions of the nearest 1/16. I've been searching for a few hours, and the one option I've found that seems to be the best is Fraction.js. However, when following examples such as here, I get improper fractions. For example:
var convertToFraction = function (decimal) {
// Round to the neareest 1/16
var f = new Fraction(decimal);
var newVal = f.toFraction();
return newVal;
};
I get 157293/2000"
if I pass in a value of 78.6465
, 3/2
if I pass in a value of 1.500
. For the 78.6465
, I would want to get 78 5/8
.
Is there something else I need to do to get it to return the value in proper form, not improper fraction form? Also, do I need to do my own rounding of the decimal to the nearest 1/16 before passing the value to Fraction
, like so?
var convertToFraction = function (decimal) {
// Round to the nearest 1/16
var rounded = (Math.round(decimal * 16) / 16).toFixed(3);
var f = new Fraction(rounded);
var newVal = f.toFraction();
return newVal;
};
Even with that, I still get an improper format.
To get the proper fractions, I just had to pass the true
argument to toFraction()
:
var newVal = f.toFraction(true);