Search code examples
javaandroidbigdecimal

How can I multiply 2 or more BigDecimals in java?


I am writing an unit converter app for android and I've been using doubles to perform the calculations and to retrieve them. I only realised now that the result is not accurate. THIS is what I wanted to do:

EditText InputInMeters = (EditText) findViewById(R.id.****);
EditText AnotherTextBoxWIO = (EditText findViwById(R.id.****);
String ValueInMeters = InputInMeters.getText().toString();
double meters = Double.parseDouble(ValueInMeters);
double kilometers = (meters * 1000);
AnotherTextBoxWIO.setText(kilometers+"");

This works well for values like 1 or 10 but for values like 123.4 the output is 0.1232(9). After research I found out abou BigDecimals and my doubt is, How can I do this (multiply 2 or more big decimals and then convert to string) but with BigDecimals?


Solution

  • BigDecimal bd1 = new BigDecimal(string);
    BigDecimal bd2 = new BigDecimal(string2);
    
    Bigdecimal result = bd1.multiply(bd2);
    System.out.println(result.toString());