Convert a numeric value with a currency symbol back to decimal using NumberFormat

I would like to convert a possible decimal value with a currency prefix to a numeric value.
For example -
The value can be like any of the following

String s1 = "£32,847,676.65";
String s2 = "£3,456.00";
String s3 = "£831,209";

I would like the result after the conversion to be like - 32847676.65, 3456.00and 831209.
I tried using the method parse()for NumberFormat this way -

NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.UK);
numberFormat.setMinimumFractionDigits(2);
Number num = nf.parse(s1);
double dd = num.doubleValue();
BigDecimal gg = new BigDecimal(dd);
System.out.println(gg);

But the result is 32847676.649999998509883880615234375that which is not entirely accurate.

I need it to be numeric, so that I can do some kind of calculation.
Can you guys guide me on what else I can try.

+5
source share
4

. :

BigDecimal gg = new BigDecimal(dd);

BigDecimal, . :

BigDecimal gg = new BigDecimal(dd).setScale(2);

BigDecimal gg = new BigDecimal(dd).setScale(2,RoundingMode.HALF_UP);
+5

BigDecimal BigDecimal (String val)

    NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.UK);
    BigDecimal gg = new BigDecimal(nf.parse(s1).toString());
    System.out.println(gg);

BigDecimal (double val) , , .

" . , BigDecimal (0.1) Java BigDecimal, 0,1 ( 1 1), 0,1000000000000000055511151231257827021181583404541015625. , 0,1 (, , ). , , , , 0,1. [...] , String "

: BigDecimal javadoc

+5

BigDecimal NumberFormat.;)

String s1 = "£32,847,676.65";
// remove the £ and ,
String s2 = s1.replaceAll("[£,]", "");
// then turn into a double 
double d = Double.parseDouble(s2);
// and round up to two decimal places.
double value = (long) (d * 100 + 0.5) / 100.0;

System.out.printf("%.2f%n", value);

32847676.65

youw ant, , , BigDecimal long .

// value in cents as an integer.
long value = (long) (d * 100 + 0.5);

// perform some calculations on value here

System.out.printf("%.2f%n", value / 100.0);
0

, , API NumberFormat, getXyzInstance DecimalFormat " ". , " , ".

NumberFormat DecimalFormat, , BigDecimal , :

DecimalFormat nf = (DecimalFormat) NumberFormat.getCurrencyInstance(Locale.UK);
nf.setParseBigDecimal(true);
BigDecimal gg = (BigDecimal) nf.parse(s1);
System.out.println(gg);

.

0

All Articles