Three ways to do this:
- Decimal Format
- String.format
- BigDecimal
Decimal Format
import java.math.RoundingMode; import java.text.DecimalFormat; public class DecimalFormatDemo { private static DecimalFormat df = new DecimalFormat("#.###"); public static void main(String[] args) { double input = 1.23456789; System.out.println(df.format(input)); df.setRoundingMode(RoundingMode.DOWN); System.out.println(df.format(input)); df.setRoundingMode(RoundingMode.UP); System.out.println(df.format(input)); } }
Output
1.235 1.234 1.235
String.format
double input = 1.23456789; System.out.println("double : " + String.format("%.2f", input)); System.out.format("double : %.2f", input);
Output
double : 1.23 double : 1.23
BigDecimal
double input = 1.23456789; System.out.println("double : " + input); BigDecimal bd = new BigDecimal(input).setScale(2,RoundingMode.HALF_UP); double newInput = bd.doubleValue(); System.out.println("double : " + newInput);
Output
double : 1.23456789 double : 1.23