To truncate decimals in Java, you can use the Math.floor
method to round down to the nearest integer, or the Math.round
method to round to the nearest integer.
Here's an example of how you can use the Math.floor
method to truncate decimals:
public class Main { public static void main(String[] args) { double num = 123.456; // Truncate the decimal part of the number double truncated = Math.floor(num); System.out.println("Truncated: " + truncated); } }
This code will truncate the decimal part of the number 123.456 and print the result to the console. The output of this code will be:
Truncated: 123.0
Here's an example of how you can use the Math.round
method to round a number to the nearest integer:
public class Main { public static void main(String[] args) { double num = 123.456; // Round the number to the nearest integer long rounded = Math.round(num); System.out.println("Rounded: " + rounded); } }
This code will round the number 123.456 to the nearest integer and print the result to the console. The output of this code will be:
Rounded: 123
Note that the Math.floor
method will always round down to the nearest integer, while the Math.round
method will round to the nearest integer using standard rounding rules (i.e. it will round up for numbers with a decimal value of 0.5 or greater).
If you want to truncate decimals to a specific number of decimal places, you can use the DecimalFormat
class from the java.text
package.
Here's an example of how you can use the DecimalFormat
class to truncate decimals to 2 decimal places:
import java.text.DecimalFormat; public class Main { public static void main(String[] args) { double num = 123.456789; // Truncate the number to 2 decimal places DecimalFormat df = new DecimalFormat("#.00"); System.out.println(df.format(num)); } }