Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Formats a number value into a fraction with optional accuracy
/*
|
|
| Formats a number value into a fraction with optional accuracy
|
|
*/
function fractionalizeValue(value, fractions)
{
// default to 16th
fractions = fractions === undefined ? 16 : fractions;
// extract whole number, remainder and our numerator
var wholeNumber = Math.floor(value);
var remainder = value - wholeNumber;
var numerator = Math.round(remainder / (1 / fractions));
var denominator = fractions;
var output = '';
var unicodeEntities = {
'1/4': '¼',
'1/2': '½',
'3/4': '¾',
'1/3': '⅓',
'1/3': '⅔',
'1/5': '⅕',
'2/5': '⅖',
'3/5': '⅗',
'4/5': '⅘',
'1/6': '⅙',
'5/6': '⅚',
'1/8': '⅛',
'3/8': '⅜',
'5/8': '⅝',
'7/8': '⅞'
};
// can we simplify our fraction, do it until we can't any more
while(numerator % 2 === 0 && denominator % 2 === 0)
{
numerator = numerator / 2;
denominator = denominator / 2;
}
if(numerator === 1 && denominator === 1)
{
wholeNumber += 1;
numerator = 0;
}
// format our output
if(wholeNumber > 0)
{
output = wholeNumber;
}
// add fraction
if(numerator > 0)
{
if(wholeNumber > 0)
{
output += ' ';
}
if(unicodeEntities[numerator + '/' + denominator])
{
output += unicodeEntities[numerator + '/' + denominator];
}
else
{
output += numerator + '/' + denominator;
}
}
return output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.