Thursday, January 16, 2025
HomeProgrammingHow to round a number to n decimal places in Java?

How to round a number to n decimal places in Java?

To round a number to n decimal places in Java, you can use BigDecimal or String.format(). Here are two methods:

1. Using BigDecimal:

import java.math.BigDecimal;
import java.math.RoundingMode;

public class Main {
public static void main(String[] args) {
double number = 123.456789;
int n = 3;

See also  How do I update Node.js?

BigDecimal rounded = new BigDecimal(number).setScale(n, RoundingMode.HALF_UP);
System.out.println(rounded); // Output: 123.457
}
}

2. Using String.format():

public class Main {
public static void main(String[] args) {
double number = 123.456789;
int n = 3;

System.out.println(String.format(“%.” + n + “f”, number)); // Output: 123.457
}
}

Both methods round the number to the specified number of decimal places.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x