check if a number is decimal or integer in kotlin - android

I would like to know how I can identify a number as decimal or integer, I was already researching how to do it but I run into some problems when using it in an if else conditional, it gives me the following error:
Operator '==' cannot be applied to 'Float' and 'Int'.
When requesting the data from the user, I save it as Float and when placing it in the conditional it generates that error. Does anyone know how I can request a number and then check if it is integer or has decimal? By the way I am using kotlin
Code:
fun main(){
val number01 = readLine()!!.toFloat()
if (number01 % 1 == 0){ // A X + B = 0
println("Solution 1: $number01")
}else{
println("Solution 2: $number01")
}
}
I already looked on the internet how to know if it is an integer or if it is a number with decimal but when using it in a conditional it generates an error.

the output from number01%1 is Float and your using == to a Int
.To correct that you have to change your code into:
fun main(){
val number01 = readLine()!!.toFloat()
if (number01 % 1 == 0f){
println("Solution 1: $number01")
}else{
println("Solution 2: $number01")
}
}

Related

I don't understand why "return" doesn't return a value [duplicate]

This question already has answers here:
Kotlin: Variable 'result' must be initialized
(3 answers)
Kotlin variable usage "variable must be initialize"
(1 answer)
Closed last month.
I'm new to kotlin and I don't know English well so "Google Translate hello!".
I want to return the values that I received during the execution of the if condition. This function iterates through the columns in the excel table until it finds the one I need and returns its number
I tried to write return#getTableValue to indicate where to return the value, but it didn't give anything, I don't understand, help
My code:
private fun getTableValue(xlWs: Sheet, groupe: String, dopgroupe: String): Int {
var gr: String
var cellNumb: Int
var res: Int
for (i in 0..20){
gr = xlWs.getRow(0).getCell(i).toString()
if (gr == groupe){
cellNumb = i
if (dopgroupe == "1") {
res = cellNumb
}
if (dopgroupe == "2") {
res = cellNumb + 2
}
}
}
return res // Error Variable 'res' must be initialized
}
You only set res inside if statements, so the compiler cannot be sure that you ever set a value to res. You can only use a variable’s value after it is guaranteed to have been set to something. In this case, the easiest solution is to give the variable an initial value at the declaration site, like this:
var res: Int = 0

Kotlin float number with 2 decimals to string without precision loss

In Android-Kotlin I am getting float number from backend (for example num = 10000000.47)
When I try to String.format it and add that number in my balanceTextview it shows it with exponent (something like 1.0E10).
I want to show number normally without exponent and with 2 decimals. (Without presicion loss!)
Tried to use DecimalFormat("#.##") but it didn't help me. Maybe I'm doing something wrong?
num = 10000000.47f
val dec = DecimalFormat("#.##")
var result = dec.format(num)
my result is: 10000000
It losts my decimal places
The issue is your number type. According to the documentation:
For variables initialized with fractional numbers, the compiler infers the Double type. To explicitly specify the Float type for a value, add the suffix f or F. If such a value contains more than 6-7 decimal digits, it will be rounded.
With an example that shows how information may get lost:
val pi = 3.14 // Double
val e = 2.7182818284 // Double
val eFloat = 2.7182818284f // Float, actual value is 2.7182817
If the value is specified as Double instead of Float, i.e.
val num = 10000000.47
instead of
val num = 10000000.47f
then your approach works as expected, but could be shortened to:
"%.2f".format(num)
(note that the shorter version will also print "100" as "100.00" which is different from your approach but potentially still desired behaviour)
If you receive a Float from the backend then the information is already lost on your side. Otherwise you should be able to fix the issue by improved parsing.
The extension function format is only available in the JVM. In Kotlin/native, you can use this instead:
fun Float.toPrecision(precision: Int) =
this.toDouble().toPrecision(precision)
fun Double.toPrecision(precision: Int) =
if (precision < 1) {
"${this.roundToInt()}"
} else {
val p = 10.0.pow(precision)
val v = (abs(this) * p).roundToInt()
val i = floor(v / p)
var f = "${floor(v - (i * p)).toInt()}"
while (f.length < precision) f = "0$f"
val s = if (this < 0) "-" else ""
"$s${i.toInt()}.$f"
}

Kotlin behaves weird in identity of boxed and unboxed numbers

In my algorithm, I have been checking identify of the int variable and nullable int,
var literal_num: Int = 1000
var literal_num_boxed: Int? = literal_num
println("***********************************")
println((literal_num === literal_num_boxed)) //print false
println("***********************************")
but when you change the number to 100 the identity is equal, am i doing wrong here?
var literal_num: Int = 100
var literal_num_boxed: Int? = literal_num
println("***********************************")
println((literal_num === literal_num_boxed)) //true
println("***********************************")
I tried the same in the kotlin documentation. its also behaving the same. check the following images.
After i edited the number to 100 it behaves the in a different way.
This is because Integer.valueOf has caches.
When you use === to compare int and Int?, autobox happens and it calls Integer.valueOf.
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
From Integer.java. low is -128 and high is 127 by default.
When autobox happens, every number from -128 to 127 will share a same Integer and your result will be true. If a number isn't in that range, a new Integer will be created and your result will be false.
Related design patterns: https://java-design-patterns.com/patterns/flyweight/

Making a calculator but no way to retrieve functions

An easy way to make an android calculator would be to have 3 separate edit text boxes and have the user in put a number, a function, and then another number like 3 + 3. This would make it easier for the app dev to store the number(s) and function(s) and perform a calculation.
Now... my calculator app has the ability to out put all the input real-time, the down side is that when I retrieve what's in the input box, i retrieve it as string (to make sure i include all the functions input-ed). I know how to retrieve numbers (by using int parse) but how do I retrieve the functions such as + - / * ? (They're the main bit!! :O). Any help would me much appreciated thanks :)
Try to use a switch that analyze and identify the correct operation. Something like this:
(I suppose the content of function EditText in a string named functionSign
...
switch(functionSign)
{
case "+": return op1+op2;
case "-": return op1-op2;
...
EDIT 2:
I suppose that user can put only the functions simbols + - / * and the operations are organized in a method:
public double calculate()
{
String operations= inputEditText.getText().toString();
StringTokenizer st= new StringTokenizer(operations);
//to calculate in input must have at last one operation and two operands
//the first token must be a number (the operation scheme is (number)(function)(numeber)...)
double result=Double.parseDouble(st.nextToken());
while(st.hasMoreTokens())
{
String s=st.nextToken();
if(s.equals("+"))
result += Double.parseDouble(st.nextToken());
else if(s.equals("-"))
result -= Double.parseDouble(st.nextToken());
else if(s.equals("*"))
result *= Double.parseDouble(st.nextToken());
else if(s.equals("/"))
result /= Double.parseDouble(st.nextToken());
else
throw new Exception();
}
return result;
}
This code is a really simple example, you must be sure that the user don't try to calculate something incomplete like:
3 + 3 -
/ 3 * 5
and similar. What the user should be able to do is your decision
You can get the operator as a string and use if statements to determine what to do:
String operator=operatorEditText.getText().toString();
if (operator.equals("+")){
//addition code here
}
else if (operator.equals("-")){
//subtraction code here
}
...

Android: Converting a set of functions into an equation

I am 99% sure that this cannot be done, however I thought I would ask to be certain.
I am attempting to create an application that calculates the required dice roll for an action in a popular tabletop war game.
The following is this calculation in Java
int x = ((WSattacker * 2) - WSdefender);
int y = (WSattacker - WSdefender);
String result;
// Calculation for a +5
if (x <= -1) {
result = "5+";
}
// Calculation for a +4
else if (x >= 0 && y <= 0) {
result = "4+";
}
// Calculation for a +3
else if (y > 0) {
result = "3+";
} else {
result = "Error";
}
return result;
Now my issue is that to avoid copywriter infringement I cannot mention the name of the game in my application, and probably cannot hard code the above calculation in the app.
This means that it is difficult to tell a potential user what the app will do.
The only solution I can think of is to make the application generic and allow the user to input the calculation required in the form of an equation.
An equation that I can place anonymously on a public board or similar.
Therefore my questions are as follows.
Is there another way of going about this?
If no, is it possible to condense the above code into a single expression/ equationi.e. one that removes the if and else statements
To answer question 2:
result = test_condition_1 ? result2_if_true : (test_condition_2 ? result2_if_true : test3_or_result2);
You can then build up 'compound' test conditions this way, and it's based upon ternary operators.
EDIT
Ternary operators are a short-hand way of writing if..then..else statments, and more information can be found in the wiki-link above. An example of its use is below, which you can compile and run:
public class TernaryTest {
public static void main(String [] args){
int x = 14;
int y = 5;
String result = ( x <= 10 ) ? "Less than 10" : "More than 10";
System.out.println("Result is: " + result);
}
}
Try running it and see the result as you change the value of x to understand how it works. Then it's possible to extend it to include and else by replacing the "more than 10" string.

Categories

Resources