You are currently viewing the BOOK: Beginning Java 2 section of the Wrox Programmer to Programmer discussions. This is a community of tens of thousands of software programmers and website developers including Wrox book authors and readers. As a guest, you can read any forum posting. By joining today you can post your own programming questions, respond to other developers’ questions, and eliminate the ads that are displayed to guests. Registration is fast, simple and absolutely free .
I would be very grateful if someone could shed some light on this simple problem.
Basically I am trying to do Exercise 2 in Chapter 2 of Ivor Horton's Begining Java 2 SDK 1.4 Edition.
The exercise asks that you take a double like 1234.5678. Put the integral part of the double into a long i.e. 1234. This part is OK. Then the exercise asks that you put the fraction into a short i.e. 5678.
This last part is where I am having problems. Other than hard-coding a fix is there a neater way of doing this. Is there a function available already that does this trick?
I am only begining with Java so any help at all would be gratefully received.
public class DisplayParts
{
public static void main(String[] args)
{
// Initialize a double variable to some value (1234.5678)
double myNumber = 1234.5678;
long integPart = 0;
short fracPart = 0;
int decPlaces = 4;
// Find the integer part
integPart = (int)myNumber;
// Find the number of Decimal places
fracPart = (short)Math.round((myNumber - integPart)*Math.pow(10,decPlaces));
System.out.println("myNumber is " + integPart + "." + fracPart);
// What happens if decPlaces > 4? How could this be rectified?
}
}
In the BigDecimal class we have a variable called "scale", that sets the number of digits.
Is there a similar field or method available in the encapsulating Double class?
(Excuse me my jargon practise)