我们不允许提出有关书籍、工具、软件库等方面的建议的问题。您可以编辑问题,以便用事实和引用来回答它。
关闭 6 年前。
是否有一个库可以将 Double 转换为 String 与整数,后跟分数?
例如
1.125 = 1 1/8
我只寻找 64 英寸以内的分数。
最佳答案
您的问题很简单,因为您确信在 C# 中分母将始终除以 64。(有人可以随意翻译 Java 版本):
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);
}
奖励:代码高尔夫
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);
}
https://stackoverflow.com/questions/379176/