Ryan
Ryan

Reputation: 67

How do I multiply two String variables?

I want to multiply two String variables and want to store the answer in a new variable. How can I do this?

I have already tried to do the simple:

String t2 = t1 * m1;

The error was that * was undefined. So, I tried adding:

import java.math.'whatever';

That didn't fix the error.

Upvotes: 4

Views: 28991

Answers (6)

Mostafa Jamareh
Mostafa Jamareh

Reputation: 1439

String t1 = "325486";

    String m1 = "7868";

    int n1 = Integer.parseInt(t1);

    int n2 = Integer.parseInt(m1);

    int n3 = n1 * n2;

    String t2 = String.format("%d", n3);

Upvotes: 0

Josh Grinberg
Josh Grinberg

Reputation: 533

Java doesn't know what it means to convert two arbitrary Strings together (i.e. what's "smelly" * "whale"?). First you need to convert the Strings to numbers, multiply those numbers together, then convert the result back to a String.

try {
    double t1_num = Double.valueOf(t1);
    double m1_num = Double.valueOf(m1);
    double t2_num = t1_num * m1_num;
    String t2 = String.valueOf(t2_num);
} catch (NumberFormatException e) {
    // called if numbers cannot be converted to Strings
}

You need the try-catch block to handle the cases when t1 and m1 contain non-digit characters, like "Ryan1" or "fifteen".

Upvotes: 1

Andreas Wederbrand
Andreas Wederbrand

Reputation: 40061

* is undefined because t1 is a String and Strings cant be used in multiplication. If t1 and m1 are stringrepresentations of numbers you can convert them to numbers (chose Integer, Float, Double or whatever is needed in your application) and then multiply. Like this (variable names are none-java-style for extra readability, no bashing about it):

    String t1  = "1.5";
    String m1 = "10";

    float t1_as_a_float = Float.parseFloat(t1);
    float m1_as_a_float = Float.parseFloat(m1);

    float t2_as_a_float = t1_as_a_float * m1_as_a_float;

    String t2 = Float.toString(t2_as_a_float);

Upvotes: 1

Cris
Cris

Reputation: 13351

use

String t2 = String.valueOf(Integer.parseInt(t1) * Integer.parseInt(m1)) 

Upvotes: 4

Akash KC
Akash KC

Reputation: 16310

First get the value from String and multiply the parsed value in following way:

double result = Double.parseDouble(t1 ) * Double.parseDouble(m1);
String t2 = Double.toString(result ); 

Have a look on Conversion between Numbers and String

Upvotes: 2

morgano
morgano

Reputation: 17422

try

String t2 = String.valueOf(Float.valueOf(t1) * Float.valueOf(m1))

Upvotes: 2

Related Questions