2

i have a double number which is "547.123456"

i just want to use this double as "547.1" like only 1 number after "."

How can i do that?

Pascal
  • 1,288
  • 8
  • 13
serkan
  • 1,237
  • 2
  • 12
  • 14

5 Answers5

5

Use BigDecimal

double f=547.123456;
BigDecimal d=new BigDecimal(f);
System.out.print( d.setScale(1, RoundingMode.FLOOR));
Nambi
  • 11,944
  • 3
  • 37
  • 49
  • 1
    +1 this is the only reliable way of ensuring that you are **always** working with `547.1`. – skiwi Mar 05 '14 at 12:15
  • @skiwi except that the snippet above use a double to create the BigDecimal, in which case the precision is already lost. Only the constructors with String should be used. – gizmo Mar 05 '14 at 12:23
  • @gizmo the precision is not lost - it is as good as the precision of the original double... – assylias Mar 05 '14 at 14:43
2

If you want to trancate a value e.g.

  47.12345 -> 47.1
  47.56789 -> 47.5 // <- not 47.6!

you can do it via floor

  double value = 47.123456;
  double result = Math.floor(value * 10.0) / 10.0;

If you want to round a value e.g.

  47.12345 -> 47.1
  47.56789 -> 47.6 // <- not 47.5!

you can do it via round

  double value = 47.123456;
  double result = Math.round(value * 10.0) / 10.0;
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
2

Use a String.format

String.format("%.1f",547.123456);

This an easiest way i think.

Sergey Shustikov
  • 15,377
  • 12
  • 67
  • 119
1

Very easily :)

double x = 47.123456;
x = (long)(x*10)/(double)10
libik
  • 22,239
  • 9
  • 44
  • 87
1

There is a general solution for every precision, you can specify your own like so:

DecimalFormat decimalFormat = new DecimalFormat("#.#");
System.out.println(decimalFormat.format(<your double>));
nikis
  • 11,166
  • 2
  • 35
  • 45