[英]Correct way to format a notation of a number with decimal scale in Java without dividing
I have done a reading about number conversions in Java
because I need to format a number inside my Android application. 我已经阅读了有关
Java
数字转换的文章,因为我需要在Android应用程序中格式化数字。
I'm currently holding a long
variable with 4 digits 我目前持有一个4位数的
long
变量
long variable_1 = 2203;
And this is what I'm looking to print 这就是我想要打印的
220.3
variable_1 = 2203;
BigDecimal bd = new BigDecimal(variable_1);
bd = bd.setScale(1, BigDecimal.ROUND_HALF_UP);
txtView_variable_1.setText(String.valueOf(bd));
Result 结果
2203.0
What am I doing wrong here? 我在这里做错了什么?
If you change the scale of a BigDecimal
, it will return a new BigDecimal
with the specified scale but with the same numerical value. 如果更改
BigDecimal
的小数BigDecimal
,它将返回具有指定小数BigDecimal
但具有相同数值的新BigDecimal
。 It won't change the interpretation of the unscaled number. 它不会改变未缩放数字的解释。 The underlying scaled number will be rescaled.
基础缩放数字将被重新缩放。
You should give the scale at the initialization of the BigDecimal in order for it to interpret correctly your unscaled number : 您应该在BigDecimal的初始化时给出比例,以便它正确地解释您未缩放的数字:
long variable_1 = 2203;
BigDecimal bd = new BigDecimal(BigInteger.valueOf(variable_1), 1);
System.out.println(String.valueOf(bd));
Which outputs : 哪个输出:
220.3
I had the same problem to round at 0.1 I managed it like this: 我有一个同样的问题要舍入到0.1,我设法做到这一点:
private BigDecimal roundBigDecimal(BigDecimal valueToRound) {
int valeurEntiere = valueToRound.intValue();
String str = String.valueOf(valeurEntiere);
int rounding = valeurEntiere == 0 ? 1 : str.length() + 1;
return new BigDecimal(String.valueOf(valueToRound), new MathContext(rounding, RoundingMode.HALF_UP));
}
In fact the int rounding depends of the number of digit of the number. 实际上,int舍入取决于数字的位数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.