回合结果分数 Apache Math Common
Round outcome Fraction Apache Math Common
是否可以对分数进行四舍五入,例如,3/2
变成 1+1/2
并且 11/2
变成 5+1/2
是使用 Apache Common Math 产生的?
尝试
Fraction f = new Fraction(3, 2);
System.out.println(f.abs());
FractionFormat format = new FractionFormat();
String s = format.format(f);
System.out.println(s);
结果:
3 / 2
3 / 2
您要找的似乎是 Mixed Number.
因为我认为 Apache Fractions 没有内置此功能,您可以使用以下自定义格式化程序:
public static String formatAsMixedNumber(Fraction frac) {
int sign = Integer.signum(frac.getNumerator())
* Integer.signum(frac.getDenominator());
frac = frac.abs();
int wholePart = frac.intValue();
Fraction fracPart = frac.subtract(new Fraction(wholePart));
return (sign == -1 ? "-" : "")
+ wholePart
+ (fracPart.equals(Fraction.ZERO) ? ("") : ("+" + fracPart));
}
是否可以对分数进行四舍五入,例如,3/2
变成 1+1/2
并且 11/2
变成 5+1/2
是使用 Apache Common Math 产生的?
尝试
Fraction f = new Fraction(3, 2);
System.out.println(f.abs());
FractionFormat format = new FractionFormat();
String s = format.format(f);
System.out.println(s);
结果:
3 / 2
3 / 2
您要找的似乎是 Mixed Number.
因为我认为 Apache Fractions 没有内置此功能,您可以使用以下自定义格式化程序:
public static String formatAsMixedNumber(Fraction frac) {
int sign = Integer.signum(frac.getNumerator())
* Integer.signum(frac.getDenominator());
frac = frac.abs();
int wholePart = frac.intValue();
Fraction fracPart = frac.subtract(new Fraction(wholePart));
return (sign == -1 ? "-" : "")
+ wholePart
+ (fracPart.equals(Fraction.ZERO) ? ("") : ("+" + fracPart));
}