Round number to fewer decimals
There are severals ways to accomplish this. The example below shows two of them. The second example is only possible if you run Java version 1.5 or later. |
import java.text.DecimalFormat; public class NumberUtil { public void roundNumber(double numberToRound) { DecimalFormat df = new DecimalFormat("0.000") ; System.out.println( "Rounded number = " + df.format( numberToRound ) ) ; //This only works with Java runtime 1.5 or later System.out.println(String.format("Rounded number = %.3f", numberToRound)); } public static void main(String[] args) { NumberUtil util = new NumberUtil(); util.roundNumber(1.23856); } } |
The output of either one of the above rounding methods is: "Rounded number = 1,239" |
Search for code examples on this site
