Java Truncate Number: Cast Double to Int

This Java example program truncates a double by casting it to an int. The fractional part is removed.
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.
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.Math.round

However: Math.floor could be used for positive values to truncate. And Math.ceil could be used for negative values.

Java program that truncates double with int cast 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); } } Output 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.Math.ceilMath.floor

Tip: The truncateSafely method removes the fractional part for negative and positive numbers.

Java program that implements truncate method 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)); } } Output 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.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls