1

Any best way to calculate numbers in string format ?

for example have

String n1 = 0.000112
String n2 = 0.000222

n1 + n2 - I can convert string to double make calculation. But after that I should convert this in string like this

n1 + n2 = string like this "0.000334"

Any best way how to do it with java ?

4 Answers4

1
    String n1 = "0.000112";
    String n2 = "0.000222";

    System.err.println( new BigDecimal( n1).add( new BigDecimal( n2)).toString());
Heri
  • 4,368
  • 1
  • 31
  • 51
0

You can use String.valueOf(double) and Double.parseDouble(String):

String result = String.valueOf(Double.parseDouble("0.01") + Double.parseDouble("0.02"));

Another option would be this (I'll leave out the parsing):

String s = "" + doubleValue;

The list of possible conversions from double to String is pretty endless.

0

Looking at your example, I am not sure if you care about the decimal precision. So for example, if I was to maintain 10 decimal places of accuracy I would try the following.

String n1 = "0.000112";
String n2 = "0.000222";

BigDecimal n1Big = new BigDecimal(n1).setScale(10,BigDecimal.ROUND_HALF_UP);
BigDecimal result = n1Big.add(new BigDecimal(n2));

String ans = result.toString();

System.out.println(ans);

I hope this helps

Gaspar
  • 159
  • 7
0

A good approach with BigDecimal has been showed in other answers. I will describe how you can do it as per your strategy in the question:

Convert string to double make calculation

  • Convert String to Double

    Double nd1 = Double.parseDouble(n1);
    Double nd2 = Double.parseDouble(n2);
    
  • Add it

    Double sum = nd1 + nd2;
    

But after that I should convert this in string

  • Then convert it back to String. Here you need to specify the format with precision.

    String s = new DecimalFormat("#.######").format(sum);
    System.out.println(s);
    

Output:
0.000334

Atri
  • 5,511
  • 5
  • 30
  • 40