chathu93
chathu93

Reputation: 21

Java get without rounding first 2 decimal digits of a double

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

Here is an example:

49455.10937 --> 49455.10

Upvotes: 0

Views: 1446

Answers (3)

DevZer0
DevZer0

Reputation: 13535

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));

Upvotes: -1

Altuğ Ceylan
Altuğ Ceylan

Reputation: 93

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)

Upvotes: 0

Sharon Ben Asher
Sharon Ben Asher

Reputation: 14348

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

Upvotes: 3

Related Questions