Numbers vs.
numerical strings
- The
"plus" operation
+ can be
used
on:
- numbers
(such as int,
float, etc)
- String
|
- The
"plus" operation
+
produces
a
different
outcome on
numbers and
String:
-
"plus" operation
+ on
number
data type means
addition:
-
"plus" operation
+ on the
String
data type means
concatenation:
Example: "12" + "34" = "1234"
|
|
|
DEMO:
demo/04-Math+String/07-string-to-num/Demo1.java
(Show the Unicode of the
String with
BlueJ)
Numerical strings
-
Numerical string:
-
Numerical string =
a
string that
only contains
digits and
optionally a
decimal point
|
Examples:
-
Important fact:
- A
numeric string is
a
string
|
I.e.:
you
cannot
perform
computations with
a numercial string:
"123" + 1 = "1231" (because + is string concatenation !)
"3.14159" + 1 = "3.141591" (because + is string concatenation !)
|
|
DEMO:
demo/04-Math+String/07-string-to-num/Demo2.java
How to
convert
numerical strings
to numbers
- Numerical strings
revisited:
-
Performing
calculation with
numbers that are
represented as
numerical string:
- You
must
first
convert the
numerical string into
a number
|
- You can convert a
number string to an
int using
Integer.parseInt( ):
int i = Integer.parseInt("123"); // i = 123 (integer)
|
- You can convert a
number string to an
double using
Double.parseDouble( ):
double x = Double.parseDouble("3.14159"); // x = 3.14159 (double)
|
|
DEMO:
demo/04-Math+String/07-string-to-num/ConvertStrToNum.java
Programming trick:
converting
int and
double
to a (number) string
- Sometimes, you
may need to
convert a
number
(int or
double)
into a (numerical) string...
- You can convert
an integer,
double or
float into
a
numerical string by:
- Concatenating the
number with
the
empty string:
""
|
Examples:
int i = 123;
double x = 3.14;
String s;
s = "" + i ; // s = "123"
s = "" + x ; // s = "3.14159"
|
|
DEMO:
demo/04-Math+String/07-string-to-num/ConvertNumToStr.java
❮
❯