0

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.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Jan Jurec
  • 49
  • 1
  • 13
  • possible duplicate of [Generating random numbers in a range with Java](http://stackoverflow.com/questions/363681/generating-random-numbers-in-a-range-with-java) – stoooops Oct 28 '13 at 18:35

1 Answers1

2

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
Christian Tapia
  • 33,620
  • 7
  • 56
  • 73