Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #349 Convert a Fraction into a Decimal value

Parse a fraction, f, into a number, a.

For example, `1 2/3` is 1.6̅.

https://en.wikipedia.org/wiki/Fraction
https://en.wikipedia.org/wiki/Decimal

import static java.math.MathContext.DECIMAL128;
import java.math.BigDecimal;
String s[] = f.split("[ /]");
int m = s.length;
BigDecimal n = new BigDecimal(s[m - 2]),
           d = new BigDecimal(s[m - 1]),
           a = n.divide(d, DECIMAL128);
if (m > 2) a = a.add(new BigDecimal(s[0]));
import static java.lang.Integer.parseInt;
String s[] = f.split("[ /]");
int m = s.length,
    n = parseInt(s[m - 2]),
    d = parseInt(s[m - 1]);
double a = ((double) n / d);
if (m > 2) a = a + parseInt(s[0]);
#include <string>
using namespace std;
int x (f.find(' ')), y (f.find('/'));
double a;
if (y == -1) a = stoi(f);
else {
    int n {stoi(f.substr(x + 1, y))},
        d {stoi(f.substr(y + 1))};
    a = double(n) / d;
    if (x not_eq -1)
        a += stoi(f.substr(0, x));
}
#include <regex>
using namespace std;
regex r {"[ /]"};
sregex_token_iterator i {
    f.begin(), f.end(), r, -1
}, n;
int x {stoi(*i++)}, y {stoi(*i++)};
double a {
    i not_eq n ?
        x + y / stod(*i) :
        x / double(y)
};
import std.stdio;
import std.regex;
import std.range;
import std.conv;
auto r = regex(r"([-]*\d*)\s*(\d+)/(\d+)");
string[] matches = [];
foreach(c; f.matchFirst(r)) mss ~= c;
double a1 = matches[1].empty ? 0 : matches[1].to!double;
double a = a1+(matches[2].to!double/matches[3].to!double)*(a1<0 ? -1 : 1);
let x = f.indexOf(' '),
    y = f.indexOf('/'),
    a = 0
if (y == -1) a = parseInt(f)
else {
    let n = parseFloat(f.substr(x + 1, y)),
        d = parseFloat(f.substr(y + 1))
    a = n / d
    if (x != -1) a += parseInt(f.substr(0, x))
}
Fractions
a := f.ToFloat;
from decimal import Decimal
from re import split
array = split('[ /]', f)
*value, num, denom = map(Decimal, array)
a = sum(value + [num / denom])
from decimal import Decimal
*value, nd = str(f).split()
num, denom = map(int, nd.split('/'))
if not value:
    a = num / denom
else:
    a = int(*value) + (num / denom)
a = sum(map(eval, f.split()))
a = f.split.map(&:to_r).sum.to_f
let a:f64 = f.split(" ").map(|n| 
	if n.contains("/") {
		let m = n.split("/").collect::<Vec<&str>>();
		m[0].parse::<f64>().unwrap()/m[1].parse::<f64>().unwrap() * if f.starts_with("-") {
			-1 as f64
		} else {
			1 as f64
		}
	} else {
		n.parse::<f64>().unwrap()
	}
).sum();

New implementation...
< >
reilas