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

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more