How to convert BigDecimal to Decimal properly?
<p>I am trying to convert a double value e.g. <code>12.55</code> to <code>BigDecimal</code> with this code:</p>

<pre><code>BigDecimal unitPrice = new BigDecimal(product.getUnitPrice());
</code></pre>

<p>As a result, I got something like this <code>12.550000000000000710542735760100185871124267578125</code> then I have to rounded it off with this code:</p>

<p><code>unitPrice.setScale(2, RoundingMode.HALF_EVEN)</code> </p>

<p>and got a result like this <code>12.55</code> which is fine. However, when I'm going to set this as a parameter for inserting to MySQL database with this code:</p>

<p><code>addProduct.setBigDecimal(4, unitPrice.setScale(2, RoundingMode.HALF_EVEN));</code></p>

<p>So when I run it, I got this SQL Error:</p>

<p><code>Data truncation: Out of range value for column 'price_per_unit' at row 2</code> </p>

<p>I know that the problem was in this code:</p>

<p><code>addProduct.setBigDecimal(4, unitPrice.setScale(2, RoundingMode.HALF_EVEN));</code></p>

<p>as I have debugged it at this line of code, the value was </p>

<p><code>12.550000000000000710542735760100185871124267578125</code></p>

<p>The column's data type in MySQL that I have set was <code>DECIMAL(3,2)</code>. </p>

<p>How come it is not working even when I rounded it off? I have tried searching for a solution and cannot find anything relevant. How do you really set the decimal properly? I assume that you know what I'm trying to do. Thanks in advance.</p>