将Double格式化为分数 [英] Format Double as Fraction

查看:396
本文介绍了将Double格式化为分数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一个库将Double转换为具有整数的String,后跟一个分数?

Is there a library that will convert a Double to a String with the whole number, followed by a fraction?

例如

1.125 = 1 1/8

我只是寻找到64英寸的分数。

I am only looking for fractions to a 64th of an inch.

推荐答案

你的问题非常简单,因为你确信分母总是会在C#中划分64.(有人随意翻译Java版本):

Your problem is pretty simple, because you're assured the denominator will always divide 64. in C# (someone feel free to translate a Java version):

string ToMixedFraction(decimal x) 
{
    int whole = (int) x;
    int denominator = 64;
    int numerator = (int)( (x - whole) * denominator );

    if (numerator == 0) 
    {
        return whole.ToString();
    }
    while ( numerator % 2 == 0 ) // simplify fraction
    {
        numerator /= 2;
        denominator /=2;
    }
    return string.Format("{0} {1}/{2}", whole, numerator, denominator);
}

奖金:Code Golf

Bonus: Code Golf

public static string ToMixedFraction(decimal x) {
    int w = (int)x,
        n = (int)(x * 64) % 64,
        a = n & -n;
    return w + (n == 0 ? "" : " " + n / a + "/" + 64 / a);
}

这篇关于将Double格式化为分数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆