0

I want to get the first 2 decimal digits (without rounding ).

Here is an example:

49455.10937 --> 49455.10

chathu93
  • 21
  • 2

3 Answers3

1

formatting to String is an expensive operation (in performance terms) this can be done with math operations:

    double x = 49455.10937;
    x *= 100;  // moves two digits from right to left of dec point
    x = Math.floor(x);  // removes all reminaing dec digits
    x /= 100;  // moves two digits from left to right of dec point
Sharon Ben Asher
  • 12,476
  • 5
  • 25
  • 42
0
double decimalValue = 49455.10937;
String decimalValueStr = String.valueOf(decimalValue);
int indexDot = decimalValueStr.lastIndexOf('.');
int desiredDigits=3;
String decimal = decimalValueStr.substring(0, (indexDot + 1) + desiredDigits);
decimalValue = Double.parseDouble(decimal);
System.out.println(decimalValue);
//49455.109 is console output (change desired digits)
  • @chathu93 you are welcome but as Sharon said, if you are worrying about performance his piece of code is more suited for this operation – Altuğ Ceylan Jan 30 '19 at 06:20
-1

You can use a formatter to format the double value as follows

StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb, Locale.US);
Double value = 49455.10937;
System.out.println(formatter.format("The value: %.2f", value));
DevZer0
  • 13,069
  • 5
  • 24
  • 48