Question

I want to generate number between 30 to 80 and for that i use:

this.length=(float)(Math.random()*50+30);

Then i have to parse a few parameters of instance to string:

result=this.name+" by "+this.smith+" in "+this.productionYear+" at "+this.length+" length";

It generates string looking like this:

Lao Che by Youta in 1327 at 75.341866 length

How could i truncate length to have less decimal precision? I would like to set it to 2 digits after dot.

Était-ce utile?

La solution

You could do this:

import java.text.DecimalFormat;

double d = 1.234567;
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(d));

Or try:

double d = 1111.234567;
String str_d = String.format("%1$.2f", d); // String.format(...) generates a new String
System.out.println("Result: " + str_d); // Now you can use it like anyother String
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top