Java

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

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

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.

This page was last updated on Aug 6, 2021 (edit link).