# Big Decimal 保留两位小数

go评论58阅读模式

Big Decimal trim to two decimal places

# 问题

``````public class BigDecimalGenerator {
public static void main(String[] args) {
BigDecimal max = new BigDecimal("50.00");
BigDecimal min = new BigDecimal("-50.00");
BigDecimal range = max.subtract(min);
System.out.println(result);
}
}
``````

Below code gives me about 14 decimal places. How can i trim it to the 2 decimal place?

``````public class BigDecimalGenerator
{     public static void main(String[] args)

{ 	BigDecimal max = new BigDecimal(&quot;50.00&quot;);
BigDecimal min = new BigDecimal(&quot;-50.00&quot;);
BigDecimal range = max.subtract(min);
System.out.println(result);     }
}
``````

# 答案1

``````setScale(int newScale, int roundingMode)
``````

Use this method on `BigDecimal`

``````setScale(int newScale, int roundingMode)
``````

using the desired scale (2) and roundingmode.

# 答案2

``````BigDecimal max = new BigDecimal("50.00");
BigDecimal min = new BigDecimal("-50.00");
BigDecimal range = max.subtract(min);
BigDecimal result = min

result = result.setScale(2, RoundingMode.HALF_UP);

System.out.println(result);
``````

``````-31.28
``````

Set the rounding mode and scale.

``````BigDecimal max = new BigDecimal(&quot;50.00&quot;);
BigDecimal min = new BigDecimal(&quot;-50.00&quot;);
BigDecimal range = max.subtract(min);
BigDecimal result = min

result = result.setScale(2,RoundingMode.HALF_UP);

System.out.println(result);
``````

Prints something like.

``````-31.28

</details>

``````

• 本文由 发表于 2020年10月2日 21:33:21
• 转载请务必保留本文链接：https://go.coder-hub.com/64172459.html
• java

go 73

go 59

go 73

go 60