我正在将 C++ 应用程序迁移到 Java。如何匹配 sprintf 的舍入行为?
int main() {
char result[20];
double dArr [6] = {5.05, 5.15, 5.25, 5.35, 5.45, 5.55};
for(int i; i< 6; i++) {
sprintf(result,"%3.1lf",dArr[i]);
cout << result << endl;
}
return 0;
}
VALUE C++ sprintf Rounding:
--------- ----------------------------------------
5.05 - 5.0 (rounding: half_down or half_even?)
5.15 - 5.2 (rounding: half_up or half_even?)
5.25 - 5.2 (rounding: half_down or half_even?)
5.35 - 5.3 (rounding: half_down or half_odd ?)
5.45 - 5.5 (rounding: half_up or half_odd ?)
5.55 - 5.5 (rounding: half_down or half_odd ?)
更新:
最大缩放 谢谢。你的测试工作完美。
但在我的代码中,我从数据库中获取的值定义为:
@Column(precision=3, scale=2) //Oracle: CLASSAVERAGE NUMBER(3,2)
private BigDecimal classaverage;
当我尝试将数字四舍五入为 BigDecimal.ROUND_HALF_EVEN 时:
System.out.println(getClassaverage() + " - " + getClassaverage().setScale(1,BigDecimal.ROUND_HALF_EVEN) );
我得到值 “5.55”四舍五入为“5.6”。
在我修改了你的测试后,我明白了为什么会这样:
@Test
public void main() {
double [] dArr = {5.05, 5.15, 5.25, 5.35, 5.45, 5.55};
for (double d : dArr) {
System.out.println(new BigDecimal(d) + " - " + new BigDecimal(d).setScale(1, BigDecimal.ROUND_HALF_EVEN));
}
}
这是我得到的:
5.04999999999999982236431605997495353221893310546875 - 5.0
5.1500000000000003552713678800500929355621337890625 - 5.2
5.25 - 5.2
5.3499999999999996447286321199499070644378662109375 - 5.3
5.45000000000000017763568394002504646778106689453125 - 5.5
5.54999999999999982236431605997495353221893310546875 - 5.5
当我将 double[]
替换为 String[]
时,您的测试会生成 BigDecimal.ROUND_HALF_EVEN
的预期值:
5.05 - 5.0
5.15 - 5.2
5.25 - 5.2
5.35 - 5.4
5.45 - 5.4
5.55 - 5.6
最佳答案
如果您想使用自己的舍入:
import java.math.BigDecimal;
public class BigDecimalFormat
{
private static int ROUNDING_MODE = BigDecimal.ROUND_HALF_EVEN;
private static int DECIMALS = 1;
public static void main(String[] args) {
double[] dArr = {5.05, 5.15, 5.25, 5.35, 5.45, 5.55};
for (double d : dArr)
System.out.println(rounded(new BigDecimal(d)));
}
public static BigDecimal rounded(BigDecimal number){
return number.setScale(DECIMALS, ROUNDING_MODE);
}
}
您似乎想要格式化一个货币数字:
public static String currencyFormat(BigDecimal n) {
return NumberFormat.getCurrencyInstance().format(n);
}
关于java - 舍入 BigDecimal 以匹配 C++ sprintf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28078794/