Home
Java
double Truncate Example
Dot Net Perls
Truncate double. Truncating a number removes the fractional part. This functionality is not the same as Math.floor, ceil or round—they affect negative or positive values in a different way.
With a cast, we can remove the fractional part. This does not help with doubles that cannot be represented by ints—but for many cases it is acceptable.
Math
Cast
Example program. Here we demonstrate Math.floor and Math.round on 2 doubles. Both of the methods change -1.5 to -2. This is not the goal of a truncate method.
However Math.floor could be used for positive values to truncate. And Math.ceil could be used for negative values.
import java.lang.Math; public class Program { public static void main(String[] args) { double test1 = 1.234; double test2 = -1.567; // ... Math.floor will always go towards negative infinity. System.out.println(Math.floor(test1)); System.out.println(Math.floor(test2)); // ... Math.round may go towards negative or positive infinity. System.out.println(Math.round(test1)); System.out.println(Math.round(test2)); // ... Casting to int will remove the fractional part. // This truncates the number. System.out.println((int) test1); System.out.println((int) test2); } }
1.0 -2.0 1 -2 1 -1
Truncate method. Here we implement a truncate() method for doubles. It uses Math.ceil if the number is negative, and Math.floor otherwise.
Tip The truncateSafely method removes the fractional part for negative and positive numbers.
import java.lang.Math; public class Program { static double truncateSafely(double value) { // For negative numbers, use Math.ceil. // ... For positive numbers, use Math.floor. if (value < 0) { return Math.ceil(value); } else { return Math.floor(value); } } public static void main(String[] args) { double test1 = 1.234; double test2 = -1.567; System.out.println(truncateSafely(test1)); System.out.println(truncateSafely(test2)); } }
1.0 -1.0
Some notes. For important numeric applications, I would use Math.floor, Math.round or Math.ceil. For cases where a simple truncation of a small value is needed, an int cast is sufficient.
With a method like truncateSafely, we can combine Math.ceil and Math.floor to avoid problems with casting to int. No Math.truncate method is present in Java 8.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.