# How does converting unit works

I want to give it a try to convert 1 serving of fruits for example 1 cup into grams or even tablespoons.

Also is there a way to display “½ Cup” value in Glide?

Hola!

Using this code from Assemblysys.com , the solution in Glide would be:

What you have to do is to use this JS code:

``````function decimalToFraction(value, donly = true) {
var tolerance = 1.0E-6; // from how many decimals the number is rounded
var h1 = 1;
var h2 = 0;
var k1 = 0;
var k2 = 1;
var negative = false;
var i;

if (parseInt(value) == value) { // if value is an integer, stop the script
return value;
} else if (value < 0) {
negative = true;
value = -value;
}

if (donly) {
i = parseInt(value);
value -= i;
}

var b = value;

do {
var a = Math.floor(b);
console.log(a)
var aux = h1;
h1 = a * h1 + h2;
h2 = aux;
aux = k1;
k1 = a * k1 + k2;
k2 = aux;
b = 1 / (b - a);
} while (Math.abs(value - h1 / k1) > value * tolerance);

return (negative ? "-" : '') + ((donly & (i != 0)) ? i + ' ' : '') + (h1 == 0 ? '' : h1 + "/" + k1);
}

return decimalToFraction(p1) + " " + p2
``````

I hope it helps you!

Saludos!

4 Likes

Woah thanks for the quality reply!
I was trying to figure out Glide’s Convert Unit Computed Column but yeah JavaScript does the work too!