I'm doing a Princeton's Algorithms course and first programming task requires to output the result in this way:
mean = 0.5929934999999997
stddev = 0.00876990421552567
95% confidence interval = [0.5912745987737567, 0.5947124012262428]
I thought about string formatting since no one in their right mind would count a number of spaces for indent:
String confidence = "95% confidence interval";
int width = confidence.length();
String f = "%-".concat(String.valueOf(width)).concat("s = ");
System.out.printf(f.concat("%f\n"), "mean", stats.mean());
System.out.printf(f.concat("%f\n"), "stddev", stats.stddev());
System.out.printf(f.concat("[%f, %f]"), confidence, stats.confidenceLo(), stats.confidenceHi());
But to my regret program truncates double to float:
mean = 0.591316
stddev = 0.009776
95% confidence interval = [0.589400, 0.593232]
So is there way to format double number in its entirety so to speak?
Use DecimalFormat for this occasion, something like:
double mean = 0.592993499999999;
NumberFormat formatter = new DecimalFormat("#0.000000000000000");
System.out.println(formatter.format(mean));
Use 16 decimal place format "%.16f"
String confidence = "95% confidence interval";
int width = confidence.length();
String f = "%-".concat(String.valueOf(width)).concat("s = ");
System.out.printf(f.concat("%.16f\n"), "mean", stats.mean());
System.out.printf(f.concat("%.16f\n"), "stddev", stats.stddev());
System.out.printf(f.concat("[%.16f, %.16f]"), confidence, stats.confidenceLo(), stats.confidenceHi());
I used the String.valueOf(aDoubleNumber)
method and changed the %f to %s in your printf statements. This worked for me.
public static void main(String[] args)
{
double mean = 0.5929934999999997;
double stddev = 0.00876990421552567;
double confidenceLo = 0.12345666612123;
double confidenceHi = 0.123456784435369;
String confidence = "95% confidence interval";
int width = confidence.length();
String f = "%-".concat(String.valueOf(width))
.concat("s = ");
// changed the %f to %s and used String.valueOf method to convert first
System.out.printf(f.concat("%s\n"), "mean", String.valueOf(mean));
System.out.printf(f.concat("%s\n"), "stddev", String.valueOf(stddev));
System.out.printf(f.concat("[%s, %s]"), confidence,
(String.valueOf(confidenceLo)), String.valueOf(confidenceHi));
}
Output:
mean = 0.5929934999999997
stddev = 0.00876990421552567
95% confidence interval = [0.12345666612123, 0.123456784435369]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.