Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>@jatan</p> <blockquote> <p>Thanks for you answer. It makes sense. Can you please explain me MathContext in the context of BigDecimal#round method.</p> </blockquote> <p>There's nothing special about <code>BigDecimal.round()</code> <em>vs.</em> any other <code>BigDecimal</code> method. In all cases, the <code>MathContext</code> specifies the number of significant digits and the rounding technique. Basically, there are two parts of every <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/math/MathContext.html" rel="noreferrer"><code>MathContext</code></a>. There's a precision, and there's also a <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/math/RoundingMode.html" rel="noreferrer"><code>RoundingMode</code></a>.</p> <p>The precision again specifies the number of significant digits. So if you specify <code>123</code> as a number, and ask for 2 significant digits, you're going to get <code>120</code>. It might be clearer if you think in terms of scientific notation.</p> <p><code>123</code> would be <code>1.23e2</code> in scientific notation. If you only keep 2 significant digits, then you get <code>1.2e2</code>, or <code>120</code>. By reducing the number of significant digits, we reduce the precision with which we can specify a number.</p> <p>The <code>RoundingMode</code> part specifies how we should handle the loss of precision. To reuse the example, if you use <code>123</code> as the number, and ask for 2 significant digits, you've reduced your precision. With a <code>RoundingMode</code> of <code>HALF_UP</code> (the default mode), <code>123</code> will become <code>120</code>. With a <code>RoundingMode</code> of <code>CEILING</code>, you'll get <code>130</code>.</p> <p>For example:</p> <pre><code>System.out.println(new BigDecimal("123.4", new MathContext(4,RoundingMode.HALF_UP))); System.out.println(new BigDecimal("123.4", new MathContext(2,RoundingMode.HALF_UP))); System.out.println(new BigDecimal("123.4", new MathContext(2,RoundingMode.CEILING))); System.out.println(new BigDecimal("123.4", new MathContext(1,RoundingMode.CEILING))); </code></pre> <p>Outputs:</p> <pre><code>123.4 1.2E+2 1.3E+2 2E+2 </code></pre> <p>You can see that both the precision and the rounding mode affect the output.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload