• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

285
Views
How does one convert an integer to a float while data binding?

I have an Int which contains a decimal number in units of tenths, so for example my int holds 308 to represent the decimal number 30.8. I want to use data binding to display this number in a TextView along with some other text. My TextView has the following text entry:

android:text="@{String.format("my value: %.1f", @{viewModel.myValue}.toFloat()/10.0f)}"

This fails to build with the following error:

[databinding] {"msg":"cannot find method toFloat() in class java.lang.Integer","file":"app/src/main/res/layout/fragment_you.xml","pos":[{"line0":163,"col0":54,"line1":163,"col1":84}]}

The value in question is defined like so:

private val _myValue = MutableLiveData<Int>()
val myValue: LiveData<Int> = _myValue

I thought this meant it was a Kotlin integer and i could call Kotlin functions on it, but apparently it's a java integer and I can't?

Why can't I call toFloat() there? How can I display this Int as a decimal number?

about 3 years ago · Santiago Trujillo
3 answers
Answer question

0

This might help you.

DataBindingConverter.kt

class DataBindingConverters {
    companion object {

        @JvmStatic
        fun convertIntegerToFloat(value: Int?): Float {
            return value/10.0f
        }

    }
}

XML import

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <data>
        <import type="com.package.DataBindingConverter" />
    </data>
.....

Bind to View

<EditText
    ...
    android:text="@={DataBindingConverter.convertIntegerToFloat(viewModel.myValue)}" />
about 3 years ago · Santiago Trujillo Report

0

In xml if you want to use casting you will have to do it the way you do in JAVA

Here to convert it to float try using ->

android:text="@{String.format(&quot;my value: %.1f&quot;, Float.valueOf(@{viewModel.myValue})/10.0f)}"

.toFloat is to be done in kotlin classes. In xml still you have to use JAVA

about 3 years ago · Santiago Trujillo Report

0

I think, it will work.

android:text="@{String.format(&quot;my value: %.1f&quot;, @{(Float)(viewModel.myValue)}/10.0f)}"
about 3 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error