Sum is giving a negative number in Kotlin - android

So here is my Kotlin Code:
val intBoth = 1_391_000_000 + 1_432_342_859
println("China plus India: " + intBoth)
And the result is negative:
China plus India: -1471624437
What went wrong here?

If you you don't select a your variable type (like Long,Float,Bytes,Shorts), the kotlin asumes it is an Integer.
The variable types have boundary conditions for representing number values.
The boundary of Integers are between -2,147,483,648 and 2,147,483,647 (It's about byte of size). The variables of your calculation of summiation are Integer so the complier expect the total value is Integer, but the result is out of the range of Integer variable type. Yo can overcome the problem by convert to Long your types of elements. Write .toLong end of the variables for converting
fun main() {
val intBoth = 1391000000.toLong() + 1432342859.toLong()
println("China plus India: " + intBoth)
}
Also you can use L instead of .toLong().
val intBoth = 1391000000L + 1432342859L

Related

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: SumbyDouble returning additional decimals

I am summing double value from arraylist its giving additional decimals as 99999, how to fix this, please guide
ex
class ExDet{var expName:String ="",var expAmount:Double = 0.0}
val arrayList = ArrayList<ExDet>()
arrayList.add(ExDet("Abc 1",45.66))
arrayList.add(ExDet("DEF 1",10.0))
arrayList.add(ExDet("Lee 1",600.89))
arrayList.add(ExDet("Ifr 1",200.9))
var amt = arrayList.sumByDouble{ it.expAmount }
Expected Value of Amount is :
Amt = 857.45
But it returns
Amt = 857.4499999
Sample Code to Test
data class ExDet(var expName:String ="" ,var expAmount:Double=0.0)
fun main(args: Array<String>) {
val arrayList = ArrayList<ExDet>()
arrayList.add(ExDet("Abc 1",45.66))
arrayList.add(ExDet("DEF 1",10.0))
arrayList.add(ExDet("Lee 1",600.89))
arrayList.add(ExDet("Ifr 1",200.9))
var amt = arrayList.sumByDouble{ it.expAmount }
println("Amount is : $amt")
}
The issue you are confronted with is that floating point numbers are build on top of base 2, not base 10.
Think how you can easily represent a third as a fraction (1/3), but when you convert to decimal you get a repeating (recurring) number after the radix point (i.e. 0.33...). Some decimal numbers are recurring when represented in base-2, e.g. x.9. The computer has a finite number of bits, so the (base-2) number is truncated. All the truncation errors can add up.
You need to round to the required precision (e.g. round(x * 100) / 100).
If you are only interested in how it is displayed then you can use the format function with something like "%.2f".
String.format("%.2f", value)

Format textField value with comma - Titanium

I have a textField value as 12345678955. I want to format this value as 1,234,567.8955
Want to seperate the value with comma.
I have tired with some codes. But it doesn't work.
Well, you would want to get your 4 decimal places you would need to divide your number by 10000:
var newNumber = parseInt($.yourTextField.value);
newNumber = Math.round(Number(newNumber)) / 10000;
console.log(newNumber); // 1234567.8955
Next you want to add your commmas:
var parts = newNumber.toString().split(".");
var num = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",") + (parts[1] ? "." + parts[1] : "");
console.log(num); // 1,234,567.8955
Thats the functionality, how you tie that to your textField and by which event listener, is yours to work out.
(answer adapted from https://stackoverflow.com/a/25127753/829989 which you could have easily found on your own)

String to display number currency in Android

I have a string
String retail = c.getString(c.getColumnIndex("retail"));
The date is being passed as "99999", I need it to print out as "999.99", how can I do this?
If you always have to add the "." 2 character before the end, this should work:
retail = retail.substring(0, retail.length()-2) + "." + retail.substring(retail.length()-2,retail.length());
This will add a dot two character before the end of the String, as you need.

How can I round numbers (2 decimal) parseXml get(field) in Android

TextView.setText(XMLdata.get("XMLField") + " mm");
input values that are expressed in an abbreviated way:
10,5858555966668 (with comma)
Which I would like to convert into:
10,58
if your XMLdata.get("XMLField") value is float u can do the following code
String finalValue = String.format(
"%.2f", XMLdata.get("XMLField"));
TextView.setText(finalValue + " mm");
if your XMLdata.get("XMLField") is String convert it into float do the above method.
TextView.setText((Math.floor(MathXMLdata.get("XMLField") * 100.0) / 100.0).toString() + " mm");
This converts 10,5858555966668 to 1058,58555966668, rounds it to 1058 and converts it back to 10,58.
Note: Math.floor always rounds down (cuts off all missing fractional numbers). If you intend to round to the closest value, use Math.round.
Thank you, thank you very much rmkrishna and Faro ((= I do it with
TextView.setText(String.format("%.2f",Double.parseDouble(XMLData.get("Son7GunlukSagis").replace(",", ".")))+ " mm");

Categories

Resources