-2
String numberS = "1,332.0";
String numberE = "10";
    try {
      double value = Double.parseDouble(numberS) * Double.parseDouble(numberE);
      Log.d("result", String.valueOf(value));
    } catch (NumberFormatException e) { }

And then, I would like to know differences between String.parseString(), String.valueOf() & toString().

  • 1
    parse them to numbers, multiply, print. Don't do this: catch (NumberFormatException e) { } though. How are you going to tell whether or not an Exception was thrown? anyway, since your code does exactly what you are trying to do .. what is the question again? – Stultuske Jan 29 '18 at 08:34
  • The toString() method returns the string representation of the object. The java string valueOf() method converts different types of values into string. – Ashish John Jan 29 '18 at 08:36
  • String.valueOf(Object) is basically just a null-safe invocation of toString() of the appropriate object. – Taher Mahodia Jan 29 '18 at 08:36
  • `String.valueOf(Object)` is simply, as shown in the `String` class, `return (obj == null) ? "null" : obj.toString();` – Zachary Jan 29 '18 at 08:38
  • 1
    1,332.0 can never be converted to double just by Double.parseDouble(). You will have to remove any character other that . (dot) & integer before parsing to double. – Ashish John Jan 29 '18 at 08:39
  • 1
    `I would like to know differences` read the Javadoc. It explains what each method does. Please don't ask us to copy-paste what you can read yourself. – Vladyslav Matviienko Jan 29 '18 at 08:43

1 Answers1

2

Firstly you have to remove the comma(,) from string to convert or parse it in double or integer, otherwise it will give java.lang.NumberFormatException: Invalid double or invalid integer. You can remove the comma(,) as,

String newNumberS = numberS.replace(",",  "");

Above line convert 1,332.0 to 1332.0. So, NumberFormatException solved. Now the whole working as,

String numberS = "1,332.0";
String numberE = "10";
     try {
         String newNumberS = numberS.replace(",",  "");
         double value = Double.parseDouble(nNumberS) * Double.parseDouble(numberE);
         log.i("tag", "value: "+value);
     } catch (NumberFormatException e) {
            //catch exception here, if occur.
     }

Now about difference between String.parseString(), String.valueOf(object) and Object.toString().

So simply if given string is null String.valueOf(Object) will prints NULL whereas Object.toString() will throw NullPointerException.

Aditya
  • 3,525
  • 1
  • 31
  • 38