Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

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("--");
}   

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote