Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to check if a double has at most n decimal places?
    primarykey
    data
    text
    <p>Currently i have this method:</p> <pre><code>static boolean checkDecimalPlaces(double d, int decimalPlaces){ if (d==0) return true; double multiplier = Math.pow(10, decimalPlaces); double check = d * multiplier; check = Math.round(check); check = check/multiplier; return (d==check); } </code></pre> <p>But this method fails for <code>checkDecmialPlaces(649632196443.4279, 4)</code> probably because I do base 10 math on a base 2 number.</p> <p>So how can this check be done correctly?</p> <p>I thought of getting a string representation of the double value and then check that with a regexp - but that felt weird.</p> <p><strong>EDIT:</strong> Thanks for all the answers. There are cases where I really get a double and for those cases I implemented the following: </p> <pre><code>private static boolean checkDecimalPlaces(double d, int decimalPlaces) { if (d == 0) return true; final double epsilon = Math.pow(10.0, ((decimalPlaces + 1) * -1)); double multiplier = Math.pow(10, decimalPlaces); double check = d * multiplier; long checkLong = (long) Math.abs(check); check = checkLong / multiplier; double e = Math.abs(d - check); return e &lt; epsilon; } </code></pre> <p>I changed the <code>round</code> to a truncation. Seems that the computation done in <code>round</code> increases the inaccuracy too much. At least in the failing testcase.<br> As some of you pointed out if I could get to the 'real' string input I should use <code>BigDecimal</code> to check and so I have done: </p> <pre><code>BigDecimal decimal = new BigDecimal(value); BigDecimal checkDecimal = decimal.movePointRight(decimalPlaces); return checkDecimal.scale() == 0; </code></pre> <p>The <code>double</code> value I get comes from the Apache POI API that reads excel files. I did a few tests and found out that although the API returns <code>double</code> values for numeric cells I can get a accurate representation when I immediately format that <code>double</code> with the <code>DecimalFormat</code>: </p> <pre><code>DecimalFormat decimalFormat = new DecimalFormat(); decimalFormat.setMaximumIntegerDigits(Integer.MAX_VALUE); // don't use grouping for numeric-type cells decimalFormat.setGroupingUsed(false); decimalFormat.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US)); value = decimalFormat.format(numericValue); </code></pre> <p>This also works for values that can't be represented exactly in binary format.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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