2009-02-18 46 views
2

我需要将十进制值转换为它们的小数等效值,类似于此previous question格式重复小数作为分数

我使用发布在其中一个答案中的代码作为起点,因为它大部分都是我所需要的。

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); 
} 

正如我所说,这个代码工作正常的大部分,但我需要采取共同的重复十进制值(0.3333333),并显示给用户作为1/3。

有没有人碰巧知道这可能是怎么做到的?

回答

4

http://mathforum.org/library/drmath/view/61579.html

以在重复部分作为分子的数字位数,取9具有重复相同数量的数字并减少分数。

例如,.3的重复与3/9相同。通过gcd(在这种情况下为3)分两边来减少,你就得到1/3。

如果您可以从终止小数中提取重复小数,您需要执行一些额外的数学运算,例如: 0.133333333。

3

我在中学学到的技术:

x = 0.33333 
10 x = 3.33333 

10x - x = 3.3333 - .3333 

9x = 3 

x = 3/9 

Reduce 3/9 to 1/3.