# How to convert from type double to type int?

• July 20th, 2011, 06:10 PM
rph
How to convert from type double to type int?
I need to convert the result of a calculation from type double to type int, what's the best way of going about this?
I need to do this because I need the results of the calculation to be the length of a rectangle that will be drawn.
Many thanks :)
• July 20th, 2011, 06:12 PM
Norm
Re: How to convert from type double to type int?
You can cast it: int i = (int)1.3;
• July 20th, 2011, 06:22 PM
rph
Re: How to convert from type double to type int?
Ok I think I got that, but BlueJ is saying that I'm having an error still.

Code Java:

```import java.awt.*; import javax.swing.*;   public class goldenrect extends JApplet { double length; public void init() { String shortSide; double shortnumb;   shortSide = JOptionPane.showInputDialog ("Enter the length of the shorter side in pixels");   shortnumb = Integer.parseInt( shortSide );   length = shortnumb * 1.6180339887;   int shortnumb2 = (int) shortnumb;   int length2 = (int) length; } public void paint ( Graphics g ) { g.drawRect( 15, 10, length2, shortnumb2 ); g.drawString( "The length of the longer side is " + length, 25, 25); } }```

It says that it cannot find the symbol- variable length2
Any ideas? Any help is greatly appreciated :)
• July 20th, 2011, 06:34 PM
Norm
Re: How to convert from type double to type int?
What line is the error on?

Is length2 a local variable in a method?
or is it a class variable know to all methods?

Local variables are only known in the method (or enclosing {}s) they are defined in.
• July 21st, 2011, 03:37 AM
JavaPF
Re: How to convert from type double to type int?
• July 21st, 2011, 04:35 AM
rph
Re: How to convert from type double to type int?
Yeah that's what the problem was, I hadn't declared length2 as a class variable, thanks :)
However now I have the problem that the conversion from double to int makes the int value 0, any ideas why this might be?

import java.awt.*;
import javax.swing.*;

public class goldenrect extends JApplet
{
double length, shortnumb;
int length2, shortnumb2;
String shortSide;
public void init()
{
String shortSide;
double shortnumb;

shortSide =
JOptionPane.showInputDialog ("Enter the length of the shorter side in pixels");

shortnumb = Double.parseDouble( shortSide );

length = shortnumb * 1.6180339887;

int shortnumb2 = (int) shortnumb;

int length2 = (int) length;

}
public void paint ( Graphics g )
{

g.drawRect( 15, 10, length2, shortnumb2 );
g.drawString( "The length of the longer side is " + length, 25, 25);
}
}
• July 21st, 2011, 04:59 AM
rph
Re: How to convert from type double to type int?
Never mind I've figured it out myself, I just had to move

int shortnumb2 = (int) shortnumb;

int length2 = (int) length;

into the public void paint class.
Thanks for all your help :)
• July 25th, 2011, 04:21 AM