Note that there are some explanatory texts on larger screens.

plurals
  1. POJava Unexpected Rounding of Double/Float
    primarykey
    data
    text
    <p>Can anyone explain the following behavior? This method is supposed to scale the loaded picture so that it is as large as it can be within certain bounds without going over.</p> <pre><code>private final File imageFile; private final ImageLoaderListener listener; private final int idealWidth; private final int idealHeight; private final float idealRatio; @Override protected BufferedImage doInBackground() throws Exception { BufferedImage origImage; BufferedImage scaledImage; int origHeight; int origWidth; float imgRatio; // Load the image. try { origImage = ImageIO.read( imageFile ); origHeight = origImage.getHeight(); origWidth = origImage.getWidth(); imgRatio = origWidth / origHeight; //imgRatio = 5/7; } catch (Exception e){ JOptionPane.showMessageDialog( AppFrame.getAppFrame(), "Could not load the image.", "Error Loading Image", JOptionPane.ERROR_MESSAGE ); return null; } // Scale the image double scaleFactor = (imgRatio &gt;= idealRatio) ? idealWidth/origWidth : idealHeight/origHeight; int scaledWidth = (int) Math.floor( scaleFactor * origWidth ); int scaledHeight = (int) Math.floor( scaleFactor * origHeight ); scaledImage = new BufferedImage( scaledWidth, scaledHeight, BufferedImage.TYPE_INT_ARGB ); AffineTransform at = new AffineTransform(); at.scale(scaleFactor, scaleFactor); AffineTransformOp scaleOp = new AffineTransformOp( at, AffineTransformOp.TYPE_BICUBIC ); scaledImage = scaleOp.filter(origImage, scaledImage); return scaledImage; } </code></pre> <p>This is the unexpected result: All of the division is rounding without my telling it to. So if I run this with <code>idealWidth=1920</code> and <code>idealHeight=925</code>, the debug variable list shows <code>idealHeight = (float) 2.0</code>. Likewise, my test picture is 532x783, and <code>imgRatio = (float) 0.0</code>. ScaleFactor is doing the same thing: the 532x783 image results in <code>ScaleFactor = (double) 1.0</code></p> <p>When I originally started to bugfix this, I had inadvertently declared the ratio variables (<code>idealRatio</code> and <code>imgRatio</code>) as <code>int</code>s. I saw this, changed them to doubles, and did a clean build, thinking it was fixed. Then I changed them to floats after doubles didn't work. Now I'm stumped. Why on earth would Java still be acting as if they were <code>int</code>s?</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.
    1. This table or related slice is empty.
    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