Search code examples
xmlandroid-studioroundingandroid-databindingandroid-mvvm

Rounding double to 2 decimal places in an xml file with databinding


<TextView
    android:text="@{'£' + String.valueOf(cartItem.product.price * cartItem.quantity)}" />

I'd like to know how to round numbers to two decimal places within an XML file which gets data via databinding. The above code is a part of what I currently have and works correctly as intended. This is a cart item and is displayed in a recycler view.

CartItem is a model. cartItem is a variable in the databinding layout of type CartItem in the xml file. Product is a model which is initialised as a variable within cartItem as product.

cartItem.product.price is a double
cartItem.quantity is an integer


Solution

  • Fixed by creating a private String total; inside CartItem

    Created getter and setter for total

    In the getter:

    public String getTotal() {
            return String.format("%.2f", quantity*product.getPrice());
        }
    

    then went to the xml file and simply put in the string total instead of doing the calculation inside of the xml file.

    <TextView
        android:text="@{'£' + cartItem.total}" />