Kotlin pass string with escaped Dollar sign - android

In our project I want to pass string with dollar sign. Final result should look like this: ~ $1300. But I get only ~ the rest is not print. By debugging I found out that the issue is the dollar sign. How I can pass strings with dollar sign? Escaping dollar sign not solving this problem.
fun setItem() {
bind(valueSubtitle = "~ \$${trx.currencyAmount}")
}
fun bind(valueSubtitle: String? = null) {
val valueSubtitleTextView = findViewById(R.id.txtValueSubtitle)
valueSubtitleTextView.text = valueSubtitle
}
I don't have issues with direct printing string with dollar sign. I have issue when I try to pass this string to other function, and only then print it.
Update
I debugged, and found out that I have issue when my number has double zero at the end: 189.00 or 123.00. These number causes the problem. Other number like 123.40 or 1152.90 shows correctly.
Update 2
Issue was with my TextView. It behaved strangely when it was printing different double numbers. It was solved when I changed android:layout_width="match_parent" to android:layout_width="wrap_content"

You could try for a literal representation.
fun main(args: Array<String>) {
val amount = "25"
val escapedString = "~ ${'$'}$amount"
printString(escapedString)
}
fun printString( str : String) {
println(str)
}

Templates are supported both inside raw strings and inside escaped strings. If you need to represent a literal $ character in a raw string (which doesn't support backslash escaping), you can use the following syntax:
itemAmount.bind(valueSubtitle = "~ \${'$'}${trx.currencyAmount}")
Looks pretty bad syntax, but will work.

Try this
class MainActivity : AppCompatActivity() {
private val trx: Transaction = Transaction(1300.00)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setItem()
}
fun setItem() {
bind(valueSubtitle = "~ \$${trx.currencyAmount}")
}
fun bind(valueSubtitle: String? = null) {
val valueSubtitleTextView: TextView = findViewById(R.id.textview)
valueSubtitleTextView.text = valueSubtitle
}
class Transaction(var currencyAmount: Double)
}

There is nothing wrong with the code you have shown. Note also that you can use several ways to escape the dollar sign and that in your specific case you wouldn't even need to escape it. Just compare with the following sample code:
data class Container(val amount : Double = 123.00)
fun main() { // used Kotlin 1.3
val trx = Container()
listOf("~ \$${trx.amount}", // your variant
"~ $${trx.amount}", // easier and works too
"""~ $${trx.amount}""", // everything in this string must not be escaped
"~ ${'$'}${trx.amount}", // actually you may only use this if you require something like shown below (e.g. if you want to print something like $none)
"""~ ${"$"}${trx.amount}""", // similar to the one before
// variants to print $none:
"~ \$none",
"~ ${'$'}none",
"""~ ${'$'}none""",
"""~ $${""}none"""
)
.forEach(::println)
}
The output of the above is:
~ $123.0
~ $123.0
~ $123.0
~ $123.0
~ $123.0
~ $none
~ $none
~ $none
~ $none
But none of these answers were the solution to your problem. As the $ in your code wasn't the problem as you found out yourself...

This should work.
fun main(args: Array<String>) {
val dollar = "~$"
val amount = 1212
println("${dollar}${amount}")
}

Related

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
}
}

Why can't i bind the result of a function to my TextView in Android Studio?

I'm trying to self-teach Kotlin with the Google Android Dev Courses (I started a week ago and have very little experience in coding).
At the end of the course that thaught me to build a working Tip Calculator, there was an optional exercise to create a similar app.
I chose to create an Animal Age Calculator but i can't manage to bind the result to its TextView.
The output that i get is Animal age: %s .
The ouput that i want is the result of either my catAgeFormula(age) or my dogAgeFormula(age)
I understand it's showing me this : <string name="animal_age">Animal age: %s</string>
But the thing i don't understand is why my binding doesn't work binding.ageResult.text = getString(R.string.animal_age)
Here is the complete function i'm not sure about :
private fun calculateAge() {
val stringInTextField = binding.userAge.text.toString()
val age = stringInTextField.toIntOrNull()
if (age == null || age == 0) {
binding.ageResult.text = "0"
return
}
when (binding.animalOptions.checkedRadioButtonId) {
R.id.option_cat -> catAgeFormula(age)
else -> dogAgeFormula(age)
}
binding.ageResult.text = getString(R.string.animal_age)
}
And the output TextView :
<TextView
android:id="#+id/age_result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="#id/calculate_button"
tools:text="Animal age : 42 years" />
This is my first post on Stack Overflow so i'm really sorry if messed up something.
Thanks in advance for you help :)
You are missing an argument on the getString method
private fun calculateAge() {
val stringInTextField = binding.userAge.text.toString()
//...
binding.ageResult.text = getString(R.string.animal_age, stringInTextField)
}
Your string is:
<string name="animal_age">Animal age: %s</string>
The %s means it expects to receive 1 String type argument. The method getString can receive 2 arguments. The first is the id of the resource string and the second a vararg that can be any number of other arguments. This is because a string defined on the resources can take up any number of other arguments, by example:
<string name="example">Example %1$s %2$d</string>
Where %2$d it would be a number expected as a second argument
val example = getString(R.string.example, "one", 2)
//Example one 2
You can refer to the official documentation for further explanations
Thanks to cutiko, i found out i was missing a variable for the code to work properly.
I added my when statement into a variable named animalAge and used it as a second argument to my getString method.
Here is the final working function :
private fun calculateAge() {
val stringInTextField = binding.userAge.text.toString()
val age = stringInTextField.toIntOrNull()
//...
val animalAge = when (binding.animalOptions.checkedRadioButtonId) {
R.id.option_cat -> catAgeFormula(age)
else -> dogAgeFormula(age)
}
binding.ageResult.text = getString(R.string.animal_age, animalAge)
}
And the final working string resource :
<string name="animal_age">Animal age: %d</string>

kotlin double with 4 number after comma in 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.

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