user3761504
user3761504

Reputation: 3

Calculate Euro Prices Using BigDecimal

I have a string with the price of 70,00 and another string with the price of 25,00

I want to add them (find the sum), and I have concluded r=that I have to use BigDecimal to accomplish it.

Here's my code:

        String CPUprice = "70,00"
        String CPU_COOLERprice = "25,00";

        BigDecimal price1 = new BigDecimal(CPUprice);
        BigDecimal price2 = new BigDecimal(CPU_COOLERprice);
        BigDecimal price_final = price1.add(price2);

        TextView finalPrice = (TextView) findViewById(R.id.final_price); // Find TextView with Final Price
        finalPrice.setText(NumberFormat.getCurrencyInstance().format(price_final)); // Set Final Price TextView with The Final Price

But, it gives the error

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.kayioulis.pcbuilder/com.kayioulis.pcbuilder.MainActivity}: java.lang.NumberFormatException: Invalid long: "0,00"

The problem is that I use the comma (,). I use it because I want to display prices in Euro and the decimals in Euro use the comma (,). Example: 10,00€ = 10€

How can I add the two prices together?

Upvotes: 0

Views: 514

Answers (1)

duffymo
duffymo

Reputation: 308988

You should use the CurrencyFormat to handle locale-specific issues like this. Convert them to decimals before you do arithmetic operations.

Looks like CurrencyFormat is having euro issues.

package money;

import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;

/**
 * CurrencyFormatTest
 * @author Michael
 * @link https://stackoverflow.com/questions/31524467/calculate-euro-prices-using-bigdecimal/31524497?noredirect=1#comment51014843_31524497
 * @since 7/20/2015 7:15 PM
 */
public class CurrencyFormatTest {

    public static void main(String[] args) {
        String CPUprice = "70,00";
        String CPU_COOLERprice = "25,00";
        System.out.println(String.format("CPU price: " + convertCurrencyToDouble(CPUprice, Locale.GERMAN)));
        System.out.println(String.format("CPU cooler price: " + convertCurrencyToDouble(CPU_COOLERprice, Locale.GERMAN)));
    }

    public static double convertCurrencyToDouble(String s, Locale locale) {
        double value = 0.0;
        if ((s != null) && (s.trim().length() > 0)) {
            try {
                NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(locale);
                value = currencyFormat.parse(s).doubleValue();
            } catch (ParseException e) {
                e.printStackTrace();
                value = 0.0;
            }
        }
        return value;
    }
}

Upvotes: 1

Related Questions