0

I am developing an algorithm, which needs to read the total price of all items purchased in a receipt.

I need to be able to parse a value from string and convert it into a double.

s = ents.get(j).getDescription();
isConvertableValue = Double.parseDouble(s.replace("$", "").trim());
boolean check = BigDecimal.valueOf(isConvertableValue).scale() >= 2;

My approach, is that I check if the string passed is in the format of 12.XX, if it is, I set it as the total price of all items bought in that receipt.

However here is the problem, if the total sum of all purchases is $12.00, if I was to convert this value into a double it would be 12.0, my algorithm only accepts values in the 12.XX format.

The same applies for numbers such as 12.10, or 12.X0, however for numbers such as 12.56 or 123.435 my algorithm works.

Does anyone know how I can get it to display a string with value 12.00 or 12.10 as 12.00/12.10 without it removing the trailing 0s.

I have searched for other posts but those do not answer my question, so essentially in this line of code

if (check) {
    return isConvertableValue;
}

Ff the converted number is in the format of 12.XX NOT 12.X then return that number, as a double, now the problem is I am not returning it as a string, I wish to return it as a double/float/long whatever how can I do this?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
E-SetPrimeEpsilon
  • 113
  • 1
  • 3
  • 9
  • 1
    Yes, there's a format command for that. Basically decimal numbers don't actually have decimal places, the "float" to wherever the significant digits are (that's why they're called "floating point"). You don't make the number have additional decimal places, you just format the number when you print it. – markspace Oct 01 '20 at 15:46
  • How would I approach thism programmatically? – E-SetPrimeEpsilon Oct 01 '20 at 15:46
  • 1
    Besides the vote to close, there's also this link: https://stackoverflow.com/questions/2538787/how-to-print-a-float-with-2-decimal-places-in-java and the tutorial isn't a bad place to start either: https://docs.oracle.com/javase/tutorial/java/data/numberformat.html – markspace Oct 01 '20 at 15:47
  • Basically to approach this programmatically the first thing you do is search the web: Google "java floating point format print" is how I got all of the above. – markspace Oct 01 '20 at 15:49
  • 1
    In addition to above, you probably don't want to use floating point types for currency. https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency – domen Oct 02 '20 at 14:53

0 Answers0