Last active
August 18, 2016 18:16
-
-
Save Gerwinnz/a1e721471e85e40d0a78119cbfca9583 to your computer and use it in GitHub Desktop.
Formats a number value into a fraction with optional accuracy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
| | |
| | |
| 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