Write a console program to declare and initialize a double variable with some va
ID: 3630141 • Letter: W
Question
Write a console program to declare and initialize a double variable with some value such as 1234.5678. Then retrieve the integral part of the value and store it in a variable of type long, and the first four digits of the fractional part and store them in an integer of type short. Display the value of the double variable by outputting the two values stored as integers.
I keep getting a NumberFormatException on parsing the short
Exception in thread "main" java.lang.NumberFormatException: For input string: "0.5678"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Short.parseShort(Unknown Source)
at java.lang.Short.parseShort(Unknown Source)
public static void exercise2(){
double number = 1234.5678;
long i = (long) Math.floor(number);
short d = Short.parseShort(String.format("%.4f", number - i));
System.out.println((int) i + "." + (int) d);
System.out.println("--");
}
Explanation / Answer
please rate - thanks
public static void exercise2(){
double number = 1234.5678;
long i = (long) Math.floor(number);
short d = (short)((number-i)*10000);
System.out.println((int) i + "." + (int) d);
System.out.println("--");
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.