C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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
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