2

What is the best way to round the price to 2 decimal places in the same in command. example: 7.254545 to 7.25 In case that the data appear as string ?

ArrayList<HashMap<String, String>> productsHashMapList;
holder._price.setText(productsHashMapList.get(position).get("price"));
  1. Using split ? so split after 2 numbers after ( . ) ?

  2. Using ( .format("%.2f", d) ) .

  3. Using xml TextView ( IF POSSIBLE ) ?

why? and please give me some info because the second way not work and this message appear : java.util.IllegalFormatConversionException: f != java.lang.String

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Anas
  • 97
  • 3
  • 9
  • Which message?? – shmosel Sep 18 '18 at 02:26
  • sorry : java.util.IllegalFormatConversionException: f != java.lang.String – Anas Sep 18 '18 at 02:30
  • Is `d` a String? If so, you'll need to convert it to `double` first. – shmosel Sep 18 '18 at 02:31
  • 1
    Use `double d = Double.parseDouble(str)` to convert string to double first then use `String rounded = String.format("%.2f",d)` to round the double to 2 dp in a string – Ricky Mo Sep 18 '18 at 02:32
  • Possible duplicate of [How to round a number to n decimal places in Java](https://stackoverflow.com/questions/153724/how-to-round-a-number-to-n-decimal-places-in-java) – Tibrogargan Sep 18 '18 at 02:54
  • @RickyMo Thx. This work , but which one is prefer ? this ? or Using split ? so split after 2 numbers after ( . ) ? – Anas Sep 18 '18 at 03:41

2 Answers2

1

First convert your string to double using

Double yourNumber = Double.parseDouble(yournumberinstring);

Then to restrict it to 2 decimal places use

String.format("%.2f", yourNumber);
AIK
  • 498
  • 2
  • 6
  • 20
-1

Here you go (this will round the number):

double val = Double.parseDouble(productsHashMapList.get(position).get("price"));
BigDecimal bd = new BigDecimal(val);
bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
holder._price.setText(""+bd.floatValue());
Snake
  • 14,228
  • 27
  • 117
  • 250
  • Why is that preferable to another method? – Tibrogargan Sep 18 '18 at 02:51
  • Why not directly initialize `BigDecimal` object by calling the String constructor? `new BigDecimal("7.254545");` – Mushif Ali Nawaz Sep 18 '18 at 02:52
  • It is preferrable because the closest one is solution 2 but that does not round numbers. That will just "cut" anything beyond 2 decimal points – Snake Sep 18 '18 at 03:01
  • The official document of Big Decimal says "Note: For values other than float and double NaN and ±Infinity, this constructor is compatible with the values returned by Float.toString(float) and Double.toString(double). This is generally the preferred way to convert a float or double into a BigDecimal, as it doesn't suffer from the unpredictability of the BigDecimal(double) constructor" – Snake Sep 18 '18 at 03:03