Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert decimal amount to text string fraction in Javascript?

I have a value returned as a number, with could be decimal number e.g. "1.15".

However, I need to format all numbers in a range to a given fraction. For example, all numbers greater than 0 but less than .2 I want to return "1/8".

I already started to do this as a series of if/else statements, but I was wondering if there was a smarter and neater way.

if (amt > 0 && amt <= .2){
    q = '1/8';
} else if (amt > .2 && amt <= .3){
    q = '1/4';
}  else if (amt > .3 && amt <= .4){
    q = '1/3';
}  else if (amt > .4 && amt <= .5){
    q = '1/2';
} else if (amt > .5 && amt <= .7){
    q = '2/3';
} else if (amt > .7 && amt <= .8){
    q = '3/4';
} else if (amt > .8 && amt <= 1.0){
    q = '7/8';
} else if (amt > 1 && amt <= 1.1){
    q = '1';
} etc.....
like image 677
Steve Avatar asked Aug 30 '11 20:08

Steve


2 Answers

Move your code into a function, and you can return from the correct branch and skip all the else statements, which cleans things up pretty dramatically:

function toFraction(amt) {
  if (amt > 0 && amt <= .2) return '1/8';
  if (amt <= .3) return '1/4';
  if (amt <= .4) return '1/3';
  if (amt <= .5) return '1/2';
  // etc
}
like image 73
meagar Avatar answered Sep 30 '22 11:09

meagar


Ratio.js has a function called .toQuantityOf().

.toQuantityOf() returns a new fraction after converting the current value of the fraction to it's approximate value based on the provided units. If multiple units are passed as arguments, then the closest match to the original value will be returned.

.toString() returns the fraction as a string.

var fraction = Ratio.parse("1.15").toQuantityOf(2,3,4,8);
fraction.toString() == "9/8";

.toLocaleString() will return mixed numbers if needed.

fraction.toLocaleString() == "1 1/8";
like image 20
Larry Battle Avatar answered Sep 30 '22 10:09

Larry Battle