Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin pass string with escaped Dollar sign

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"

like image 610
Rafael Avatar asked Sep 27 '18 04:09

Rafael


3 Answers

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)
}
like image 134
Saikrishna Rajaraman Avatar answered Oct 18 '22 23:10

Saikrishna Rajaraman


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.

like image 1
Jeel Vankhede Avatar answered Oct 18 '22 22:10

Jeel Vankhede


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)
}
like image 1
Sarath Kn Avatar answered Oct 18 '22 23:10

Sarath Kn