kotlin double with 4 number after comma in Android - android

The default of Double in android kotlin is 1121.57. How to convert it to 1.121,5767 to make 4 number after comma? even though behind the comma is 0 like this: 1.121,0000

You could write an extension function for Double and use a German format for the output, like this:
fun main() {
val myDouble: Double = 1121.57
val anotherDouble: Double = 100000.99
println(myDouble.format(4))
println(anotherDouble.format(4))
}
fun Double.format(digits:Int) = String.Companion.format(
java.util.Locale.GERMAN,
"%#,.${digits}f",
this
)
It returns the following String
1.121,5700
100.000,9900

please pass your value to the following function and let me know if it works for you.
fun formattedNumber(number: Double): String{
val formattedNumber = String.format("%.7f", number)
val split = formattedNumber.split(".");
val str = StringBuilder(split[1])
str.insert(3, ',')
return "${split[0]}.${str}"
}

Take a look at the BigDecimal class. You can easily set the scale to 4 digits and it can be created with a Double.

Related

Big problem in Kotlin not cast dynamically like Apple in swift. How can i do?

I have a firebase realtime database
with this simple scheme:
admin
price1: 5
if i get database in kotlin:
val result = it.value as MutableMap<String, Any>
When i try to get price1
var price1 = result["price1"] as Long
price1 = price1 + 1
(PRICE1 can be Double or Int)
the problem is that if price 1 is 5.5 obviously app killed, but if price 1 is 5, works perfectly.
In swift, i put Double every time and it never gives problems
I find it a bit silly to have to check if it is a double or an int without a comma to be able to do the sum
// im doing this at the moment
var price1 = result["price1"].toString()
if (price1.contains(".")){
println(price1.toDouble() + 1)
}else{
println(price1.toInt() + 1)
}
Exist other simple way?
Thanks everyone
Kotlin is very strict about types, which is important for type safety.
In your case, you get a value of type Any out of result. It could be anything, not only an Int or a Double. You know that it can only be an Int or a Double, but the compiler doesn't. Many languages allow implicit stuff like type conversion (int to double), type widening (int to long), etc. But these are often sources of nasty errors. See also this discussion Does anybody find Kotlin’s Type Casting disgusting?
Regarding your code: To test a value for its type you use is.
Here is an example of how you could increment by one:
fun increment(value: Any): Any {
return when (value) {
is Double -> value + 1.0
is Int -> value + 1
else -> throw Exception("Value is neither a Double nor an Int")
}
}
And you would use it like this:
val result: MutableMap<String, Any> = mutableMapOf(
"price1" to 3,
"price2" to 3.45
)
var price1: Any = result["price1"]!! // 3
price1 = increment(price1)
println(price1) // 4
price1 = increment(price1)
println(price1) // 5
var price2: Any = result["price2"]!! // 3.45
price2 = increment(price2)
println(price2) // 4.45
price2 = increment(price2)
println(price2) // 5.45
I don't know if Kotlin will ever have union types. Then a declaration like this would be possible:
val result: MutableMap<String, [Int|Double]> // invalid code
In kotlin all numerable types like Long, Int, Double etc inherit abstract class Number
So your map declaration could be Map<String, Number>.
The Number may be easily converted to Double or any other numerable type and then you can work with it as you do in swift:
val map = hashMapOf<String, Number>(
"1" to 5.5,
"2" to 5
)
var value1 = requireNotNull(map["1"]).toDouble()
val value2 = requireNotNull(map["2"]).toDouble()
value1++
PS: never use serialization to string as a way to check a type, you can use is operator as #lukas.j suggested

How to detect the last string of a TextView contains 0 to 9

I'm a beginner in Android software development. I'm making a calculator app to test my skills. In a calculator there are 0-9 numeric and some others operators like +, -, *, / etc.
In the time of Equal functionality, I have to make sure that the last string of the TextView has any number (0-9), not any operators.
My equal fun is like that:
fun onEqual(view: View) {
if (tv_input.text.contains("0-9")) {
Toast.makeText(this, "Last string is a number, not operator", Toast.LENGTH_SHORT).show()
}
}
You need to use Kotlin regular expression matches
val lastString = "573" // input
val pattern = "-?\\d+(\\.\\d+)?".toRegex()
/**
-? allows zero or more - for negative numbers in the string.
\\d+ checks the string must have at least 1 or more numbers (\\d).
(\\.\\d+)? allows zero or more of the given pattern (\\.\\d+)
In which \\. checks if the string contains . (decimal points) or not
If yes, it should be followed by at least one or more number \\d+.
**/
val isLastString = pattern.matches(lastString)
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/ends-with.html
fun String.endsWith(
suffix: String,
ignoreCase: Boolean = false
): Boolean
Returns true if this string ends with the specified suffix.
Thanks everyone.
I did my own solution.
Here is the code I've wrote:
fun onEqual(view: View) {
if (!tv_input.text.toString().equals("")) {
val last = tv_input.text.toString()
val lastNumber: String = last.get(last.length - 1).toString()
Toast.makeText(this, lastNumber, Toast.LENGTH_SHORT).show()
}else {
return
}
}

Whats the Kotlin Syntax called where you have two names after var or val: var (name1, name2) =

I downloaded a project and I'm not really sure what exactly the following line does:
val (episode, setEpisode) = remember { mutableStateOf<EpisodeDetail?>(null) }
The only thing I don't get is why there are two names after the "val" word.
I tried to google for it but I really don't know the name of the syntax.
It's called a Destructuring Declaration
https://kotlinlang.org/docs/destructuring-declarations.html
You may have seen something similar in JavaScript when you have an object, and you can extract the keys to variables with the following
const { key1, key2 } = { key1:"first", key2:"second", ignored:"third" };
console.log(key1, key2) // first second
If you have a data class Kotlin will create the component<N> functions for you.
class MyClass (val myStr: String, val myInt: Int, val myBool: Boolean) {
operator fun component1(): String = myStr
operator fun component2(): Int = myInt
operator fun component3(): Boolean = myBool
}
fun main() {
val x = MyClass("Hello", 5, false)
val (y, _, z) = x // use _ to ignore values you don't need
println(y) // Hello
println(z) // false
}
Unlike Javascript which uses the key names, Kotlin data classes use field ordering (by defining your own component<N> functions you could swap the order of destructuring).

Format number using decimal format in kotlin

I am facing an issue where I need to do some calculations with a number like for example 5000,00 multiplied it by (1,025^3).
So in this case 5000,00 * (1,025^3) = 5385,45
So my question is, how can I format the number 5385,45 to be like 5.385,45 using decimal format maybe?
I tried by myself and I did this piece of code that outputs 5385,45 in the app but not 5.385,45
var interestValue = (5000,00*(Math.pow(1.025,yearValue)))
val number = java.lang.Double.valueOf(interestValue)
val dec = DecimalFormat("#,00")
val credits = dec.format(number)
vValueInterest.text = credits
This is the format you need:
val dec = DecimalFormat("#,###.##")
will print:
5.384,45
if you need always exactly 2 digits after the decimal point:
val dec = DecimalFormat("#,###.00")
val num = 1.34567
val df = DecimalFormat("#.##")
df.roundingMode = RoundingMode.CEILING
println(df.format(num))
When you run the program, the output will be:
1.34
Check:
https://www.programiz.com/kotlin-programming/examples/round-number-decimal
The "most Kotlin-esque" way I found to do this sort of formatting is:
"%,.2f".format(Locale.GERMAN, 1234.5678) // => "1.234,57"
"%,.2f".format(Locale.ENGLISH, 1234.5678) // => "1,234.57"
"%,.2f".format(1234.5678) // => "1,234.57" for me, in en_AU
Note though that even though this is Kotlin's own extension method on String, it still only works on the JVM.
For those looking for a multiplatform implementation (as I was), mp_stools is one option.
Used:
%.numberf
fun main(args: Array<String>) {
var A: Double
A = readLine()!!.toDouble()
var bla = A*A
var calculator = 3.14159 * bla
println("A=%.4f".format(calculator))
}
Try val dec = DecimalFormat("#.###,00"). For examples of DecimalFormat check this link.

How to convert char to ascii value in kotlin language

I am developing an android application with kotlin in which I need to convert an string character to its ASCII value,
fun tryDiCript(cypher: String) :String {
var cypher = "fs2543i435u#$#g###sagb#!#12416###"
var originalText = ""
var regEx =Regex("[a-z]")
for(char in regEx.findAll(cypher))
{
originalText += (char.value.toInt()).toString()
}
return originalText
}
this tutorial website showed me to use char.toInt() but it gives runtime error saying
Caused by: java.lang.NumberFormatException: Invalid int: "u"
so how if anyone knows hot to convert char to ASCII value please help me.
char.value is a String. When you call String.toInt(), it is expecting a numeric string such as "1", "-123" to be parsed to Int. So, "f".toInt() will give you NumberFormatException since "f" isn't a numeric string.
If you are sure about char.value is a String containing exactly one character only. To get the ascii value of it, you can use:
char.value.first().code
Since Kotlin 1.5
if your variable is of type char for example 'a' you can simply use a.code.
The old methods (e.g. toByte()) are deprecated now.
You said ascii, not unicode. So it's easy.
This is an example that shows you how to convert a char ('A') to it's ascii value.
fun main(vararg args: String) {
println('A'.toByte().toInt())
}
The output is what we expected, 65.
Note this doesn't work with unicode.
Edit 1
I guess this to work.
fun tryDiCript(cypher: String): String {
var cypher = "fs2543i435u#$#g###sagb#!#12416###"
var originalText = ""
var regEx = Regex("[a-z]")
for(char in regEx.findAll(cypher))
originalText += char.value[0].toInt().toString()
return originalText
}
And I recommend you to use StringBuilder.
fun tryDiCript(cypher: String): String {
var cypher = "fs2543i435u#$#g###sagb#!#12416###"
val originalText = StringBuilder()
var regEx = Regex("[a-z]")
for(char in regEx.findAll(cypher))
originalText.append(char.value[0].toInt())
return originalText.toString()
}
I checked #ice1000's answer, I found the block below does not work.
fun main(vararg args: String) {
println('A'.toByte().toInt())
}
As we can see in the Kotlin Documentation String - Kotlin Programming Language,the toByte() function of String "Parses the string as a signed Byte number and returns the result." If the the content of the string is not a number, it will throw a java.lang.NumberFormatException.
But there is another function of String called toByteArray(),this function does no require the content of the string being numbers. My code is as following:
String tempString = "Hello"
val tempArray = tempString.toByteArray()
for (i in tempArray){
println(i.toInt())
}
Attention that toByteArray() function's definition in kotlin's documentaion:
fun String.toByteArray(
charset: Charset = Charsets.UTF_8
): ByteArray
The default charset is UTF-8, if you would like to use other charset, you can modify it with the parameter.

Categories

Resources