w3resource

Java: Get whole and fractional parts from a double value


Split Whole and Fractional Parts

Write a Java program to get whole and fractional parts from a double value.

Sample Solution:

Java Code:

import java.util.*;
  public class Example2 {
  public static void main(String[] args) {
  double value = 12.56;
  double fractional_part = value % 1;
  double integral_part = value - fractional_part;  
  System.out.print("\nOriginal value: "+value);
  System.out.print("\nIntegral part: "+integral_part);
  System.out.print("\nFractional part: "+fractional_part);
  System.out.println();  
  }
}

Sample Output:

Original value: 12.56                                                  
Integral part: 12.0                                                    
Fractional part: 0.5600000000000005

Flowchart:

Flowchart: Get whole and fractional parts from a double value.



For more Practice: Solve these Related Problems:

  • Write a Java program to extract the whole and fractional parts from a double using only arithmetic operations.
  • Write a Java program to convert a double to its whole and fractional components without relying on Math.floor or Math.ceil.
  • Write a Java program to split a double into whole and fractional parts by converting it to a string and parsing the result.
  • Write a Java program to implement a method that returns both parts in a custom object and tests it with various double values.

Go to:


PREV : Round Up Integer Division.
NEXT : Check if Double is Integer.


Java Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.