0

I have double values like 0.0345333 or 1.0897777 and I want to convert them to 0.034 and 1.089 in Java?

How can I do it?

I want to convert the values, not print them since I need it for calculation.

I find the following way but I am looking for simple way. double score=(tff* idf); DecimalFormat df = new DecimalFormat("#.###"); p.score=Double.parseDouble(df.format(score));

user3586943
  • 89
  • 1
  • 1
  • 7

3 Answers3

2

If you want to display the result use.

String.format("%1$,.3f", myDouble);

But if you need to truncate the numbers you could use:

double number = 1.0897777;
double result = ((int)(number*1000))/1000d;//1.089
Gogutz
  • 2,005
  • 17
  • 19
1

This will truncate value to 3 decimal places:

value = ((int)(value*1000))/1000.0;

This will round to 3 decimal places:

value = (double)Math.round(value*1000)/1000;

For example:

double d1 = 0.0345333;
d1 = (double)Math.round(d1*1000)/1000;
System.out.println(d1); // 0.035

double d2 = 0.0345333;
d2 = ((int)(d2 *1000))/1000.0;
System.out.println(d2); // 0.034
Anubian Noob
  • 13,426
  • 6
  • 53
  • 75
1

You can also use BigDecimal

BigDecimal value = new BigDecimal(1.0897777);
value = value.setScale(3, RoundingMode.DOWN);
d.moncada
  • 16,900
  • 5
  • 53
  • 82
  • 1
    If you are doing "Rounding" type calculations and want to continue tow work with the results rather than just display them, then this is almost ceratinly the best answer. A double or float will almost always get jacked up during such a rounding operation (rounding 1.0897777 back into a double will end up as 1.089000001 or something). – Bill K May 05 '14 at 16:16