Published
Edited
Dec 31, 2018
Importers
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function parseFractionOrDecimal(input_string) {
let input_type, input_value;
if (input_string.indexOf("/") !== -1) {
let splits = input_string.split(" ");
let combined = 0;
for (let s = 0; s < splits.length; s++) {
let initial_split = splits[s];
if (initial_split.indexOf("/") !== -1) {
let [numerator, denominator] = initial_split.split("/");
if (denominator.trim() === "") denominator = 10;
combined += parseFloat(numerator) / parseFloat(denominator);
} else {
let parsed = parseFloat(initial_split);
if (!isNaN(parsed)) {
combined += parsed;
}
}
}
input_type = "fraction";
input_value = combined;
} else {
input_type = "decimal";
input_value = parseFloat(input_string);
}
return [input_value, input_type];
}
Insert cell
function reconstructString(output_array) {
let [input_value, input_type] = output_array;
if (input_type === "decimal") {
return input_value;
} else {
let integer = parseInt(input_value);
let decimal = precisionRound(input_value - integer, 4);
let fraction = getFraction(decimal);
return integer + " " + fraction[0] + "/" + fraction[1];
}
}
Insert cell
function getFraction(decimal) {
let numerator = decimal * 10;
let denominator = 10;
// from https://stackoverflow.com/a/4652513/8691291
var gcd = function gcd(a, b) {
return b ? gcd(b, a % b) : a;
};
gcd = gcd(numerator, denominator);
return [numerator / gcd, denominator / gcd];
}
Insert cell
function precisionRound(number, precision) {
let factor = Math.pow(10, precision);
return Math.round(number * factor) / factor;
}
Insert cell
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more