1

I want to round off any double to a String with 2 decimal places in Java. I have tried using DecimalFormat but it doesn't give the expected results. Any help would be appreciated.

Ex: I/P: 3402100.5323

I want to convert this to:

O/P: 34.02

I've tried using DecimalFormat("##,##,##0.00", new DecimalFormatSymbols(Locale.US)) but this results in 34,02,100.53 whereas I want it to output 34.02

PS: If the I/P is 34.02 I would expect it to remain same even after applying the formatting

6 Answers6

2

In my opinion, this can be achieved in 2 steps:

  1. Transform the number into your customised round-off. (3402100.5323 to 34.021005323). Divide the input with power of 10 to make it round to 2 digits.

  2. Then transformed number can be pretty-printed to truncate value after 2 decimals (34.021005323 to 34.02)

    public static void main(String[] args) {
      double input = 3402100.5323;
    
      double output = input / getDivisor(input);
      System.out.printf("%.2f%n", output);
    }
    
    private static double getDivisor(double input) {
      int length = String.valueOf((long) input).length();
      return Math.pow(10, length - 2) ;
    }
    

Output: 34.02

  • This is a good solution. It uses some maths instead of the heavy string manipulation in my answer. Casting the double to long and checking its string length is really clever. – Kirit Jan 06 '21 at 14:27
1

I think what you're looking for is the java.math.BigDecimal class (https://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html).

In your case, it would look like this:

BigDecimal rounded = BigDecimal.valueOf(yourDoubleValueHere).setScale(2, BigDecimal.ROUND_HALF_UP);
System.out.println(rounded); // 34.02

It can replace doubles (with more complex syntax though) by basically storing numbers in their decimal form, which means you could make operations on it and keep having two decimal places and avoid rounding issues.

EDIT: after thinking about it, it's probably overkill since you only want to get a String with the rounded value, but I'll leave it there just in case.

  • This seems like a _wild_ stab in the dark. – rzwitserloot Jan 06 '21 at 13:53
  • @rzwitserloot Nah, "**always** keep 2 decimal places" means using a decimal representation. OP appears to be making a request that's poorly defined to the point of inconsistency. – chrylis -cautiouslyoptimistic- Jan 06 '21 at 14:29
  • going from 'keep 2 decimal places' to 'surely OP has an underlying need for BD' is a crazy jump in logic. Perhaps they are doing currency and should be storing cents in a long instead of dollars in a double. Perhaps there is no need for perfect accuracy, there is just a need for rounding. – rzwitserloot Jan 06 '21 at 16:19
  • @rzwitserloot The truth is, I read OP's question a bit too fast, didn't notice that it was just about getting the right string, and immediately thought that this was the best thing to rely on. – Corentin Colas des Francs Jan 06 '21 at 22:09
1

Turning one number into something completely different is, naturally, not the job of decimalformat.

To get from a number representing 3402100.5323 to the string "34.02", first you'd have to get a number that is closer to "34.02". In other words, divide by 10000.0 first.

From there, String.format("%.2f") seems like an easy path: That renders any double to a string, but never using more than 2 digits after the decimal separator. If you want 3400000.123 to turn into "34.00" and not "34", you can make that String.format("%.02f") to force the zeroes.

public String renderWhateverThatIs(double in) {
    return String.format("%.02f", in / 100000.0);
}

renderWhateverThatIs(3402100.5323);
> 34,02

Note that the machine locale will dictate if you see a dot or a comma as separator. You can force the issue by explicitly passing a locale to format.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72
1

I don’t believe you can achieve what you want (First 4 digits converted into a 2 digit double with 2 decimal places) in a single step. I’ll break down the steps for an approach that I would try:

Convert the input double to a string

double d = 3402100.5323;
String dStr1 = String.valueOf(d); // dStr1 will be “3402100.5323”

Next, remove the decimal from the string

String dStr2 = dStr1.replace(‘.’,’’); // dStr2 will be “34021005323”

Then, grab the first 4 digits you are interested in

String dStr3 = dStr2.substring(0,4); // dStr3 will be “3402”

Finally, insert a decimal point

String result = dStr3.substring(0,2) + “.” + dStr3.substring(2); // result will be “34.02”
Kirit
  • 305
  • 1
  • 3
  • 8
0

You can use format for this try this out it work 100% for me.

String.format("%.2f", value)

Helpful link

https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax

ahmad bajwa
  • 966
  • 2
  • 10
  • 30