Wednesday, February 24, 2016

Display a double/float data up to some decimal places?

This is a very common use case while displaying some data to users[UI]

To display a double value up to 8 decimal places, below example code can be used.

import java.text.DecimalFormat;
DecimalFormat df = new DecimalFormat("#.00000000");
df.setMaximumFractionDigits(8);
double res=(long)(2/3)
System.out.println(df.format(res));


*** "#.00000000" pattern is used to keep the numbers exactly up to 8 decimal places. If this pattern is not used then if the res=1.25, it would print 1.25


*** But the above pattern will not print the leading zero, to print that use "0.00000000"

No comments:

Post a Comment