Index

Android apps - Numbers


If you want a user to enter a number
Calculation and conversion
If you want a number to be output to the screen
Random numbers

All variables in app/java/com.(the project name)/MainActivity must be defined. Define global variables at the start of the class, before the "onCreate" method. Casual variables only used within a method can be defined within the method. The useful number types are double (real) and int (integer). Here are definitions for two variables called "realFld" and "intfld".

double realFld = 0.0; int intfld = 0;

If you want a user to enter a number:


Calculation and conversion

Converting a string to a double is shown above. Converting a double to a (formatted) string is shown below.

Rounding - both "gmAmt" and "ozAmt" must be real (double):

gmAmt = Math.round(ozAmt * 28.35);

Extracting the decimal part of a number:

decimal = fld - Math.floor(fld);

Making the integer "intFld" into a double called "realFld" (I've defined realFld at this point, but you don't have to):

double realFld = (double) intFld;

Making double called "realFld" into an integer "int2Fld":

int int2Fld = (int) realFld;

It might be a good idea to truncate (using Math.floor()) or round (using Math.round()) first!

Arithmetic - please note - this is IMPORTANT! Java tends to do either integer or real arithmetic. If it is doing integer arithmetic, then it truncates as it goes. And it does integer arithmetic if the numbers are integers. So 5/2 will produce 2, not 2.5, EVEN if you assign the result to a real. Grr!!! The way round this, if you really want real arithmetic, is to make all your numeric constants into reals. 5.0/2.0 will give you 2.5.

Otherwise, arithmetic is similar to most programming languages.


If you want a number to be output to the screen:


Random numbers

Random numbers are a class in Java, so before you use them, you need to set up an object. This is only done once. It is a definition, not a bit of code, so can be done at the start, before any methods. (These starting definitions I call global variables, which is NOT a Java term. But that's what they are!)

static Random myRand = new Random();

When you want an integer random number, this puts a value, 0 <= randomInt < range, into the variable 'randomInt' (or anything else you want to call it).

int randomInt = myRand.nextInt(range);

When you want a double random number, this puts a value, 0.0 <= randomDouble < 1.0, into the variable 'randomDouble' (or anything else you want to call it).

double randomDouble = myRand.nextDouble();

It should give a DIFFERENT sequence each time the app is run.


© Jo Edkins 2016 - Index to Android app index