简体   繁体   English

在BigDecimal上将分数递归到十进制

[英]Recurring fraction to decimal on BigDecimal

There are many ways to convert a rational number into a decimal with a recurring part (in other words, 10/3=3.(3) , where (3) indicates that it repeats forever). 有许多种方法可以将有理数转换为带有重复部分的十进制数(换句话说, 10/3=3.(3) ,其中(3)表示它永远重复)。 But these only work if the numerator and denominator are integers. 但是这些仅在分子和分母是整数的情况下有效。 What can we do if the numerator or denominator is a double? 如果分子或分母是双精度数怎么办? For example, how can we find that 例如,我们如何找到那个

1/0.3 = 3.(3)

UPDATE: This works but only for int numbers. 更新:这有效,但仅适用于整数。

http://www.programcreek.com/2014/03/leetcode-fraction-to-recurring-decimal-java/ http://www.programcreek.com/2014/03/leetcode-fraction-to-recurring-decimal-java/

Let split the problem in two pieces: 让我们将问题分为两部分:

  • Convert 1/0.3 to N/M form 转换1/0.3N/M形式
  • Convert N/M to ab(c) form N/M转换为ab(c)形式

Lets convert 0.3 to M/N form (which give us 3/10 ). 让我们将0.3转换为M/N形式 (给我们3/10 )。

    String input = "123.456";
    String[] parts = input.split("\\.");
    String whole = parts[0];
    String fraction = parts[1];

    int wholeInt = Integer.parseInt(whole);
    int fractionInt = Integer.parseInt(fraction);
    int multiplier = pow10(fraction.length());
    int n = wholeInt * multiplier + fractionInt;
    int m = multiplier;

    System.out.println(n + "/" + m);

I used function pow10 which simply returns 10 power input. 我使用了pow10函数,该函数仅返回10个电源输入。

Now we need divide 1 by 10/3 it is easy N1/M1 divided by N2/M2 it is simply (N1*M2)/(N2*M1) . 现在我们需要将1除以10/3 ,就很容易将N1/M1除以N2/M2就是(N1*M2)/(N2*M1)

We get our result in form N/M now (we also need to normalize it by dividing both part by GCD(N, M ) 我们现在以N/M形式获得结果(我们还需要通过将两个部分除以GCD(N, M )来对其进行归一化

Now we ready to solve main problem. 现在我们准备解决主要问题。

First of all get whole part 首先得到整个部分

    int whole = n/m;

then find fraction and repeating part 然后找到分数并重复部分

    int current = n%m;
    StringBuilder sb = new StringBuilder();
    List<Integer> controlSet = new ArrayList<>();
    while((!controlSet.contains(current))){
        int currentDigit = current *10 / m;
        sb.append(currentDigit);
        controlSet.add(current);
        current = current *10 - m * currentDigit;
    }
    String fraction = sb.toString().substring(0, controlSet.indexOf(current));
    String repeat = sb.toString().substring(controlSet.indexOf(current));

Here we just divide in loop getting result number by number. 在这里,我们只是循环获取结果编号。

Main trick then number starts to repeat when we meet current that we already use. 主要技巧然后当我们遇到已经使用的current ,数字开始重复。

Now you need to take all parts together. 现在,您需要将所有部分放在一起。 Implement GCD (lots of implementation over internet). 实施GCD (通过互联网大量实施)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM