gpt4 book ai didi

java - 将 float 转换为字符串分数表示形式

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:44:09 26 4
gpt4 key购买 nike

在 Java 中,我试图找到一种将 float 转换为分数字符串的方法。例如:

float num = 1.33333;
String numStr = Convert(num); // Should return "1 1/3"

float num2 = 1.333;
String numStr2 = Convert(num2); // Should also return "1 1/3"

float num3 = 0.5;
String numStr3 = Convert(num3); // Should return "1/2"

float num4 = 2.25;
String numStr4 = Convert(num4); // Should return "2 1/4"

知道如何在 Java 中执行此操作吗?

最佳答案

最简单的方法可能是反复试验。

public static String toFraction(double d, int factor) {
StringBuilder sb = new StringBuilder();
if (d < 0) {
sb.append('-');
d = -d;
}
long l = (long) d;
if (l != 0) sb.append(l);
d -= l;
double error = Math.abs(d);
int bestDenominator = 1;
for(int i=2;i<=factor;i++) {
double error2 = Math.abs(d - (double) Math.round(d * i) / i);
if (error2 < error) {
error = error2;
bestDenominator = i;
}
}
if (bestDenominator > 1)
sb.append(' ').append(Math.round(d * bestDenominator)).append('/') .append(bestDenominator);
return sb.toString();
}

public static void main(String... args) {
System.out.println(toFraction(1.3333, 1000));
System.out.println(toFraction(1.1428, 1000));
for(int i=1;i<100000000;i*=10) {
System.out.println("PI "+i+": "+toFraction(3.1415926535897932385, i));
}
}

打印

1 1/3
1 1/7
PI 1: 3
PI 10: 3 1/7
PI 100: 3 14/99
PI 1000: 3 16/113
PI 10000: 3 16/113
PI 100000: 3 14093/99532
PI 1000000: 3 140914/995207
PI 10000000: 3 244252/1725033

关于java - 将 float 转换为字符串分数表示形式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5968636/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com