Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thousands separator formatting with Databinding

I have a ViewModel that looks like this:

public class OrderViewModel {
    double price = 23748.89;
}

and a layout that I bind the OrderViewModel to:

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

    <data>

        <variable
            name="order"
            type="com.example.viewmodel.OrderViewModel"/>

    </data>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:orientation="horizontal">


        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@{@string/price_format(order.price)}"/>

    </LinearLayout>

</layout>

The formatting string that is used looks like this:

<string name="price_format">%+.2f $</string>

which nicely adds the $ sign and reduces the float representation to 2 decimals.

Outcome looks like

1234.89

Now I want to replace the decimal point with a comma and add a thousands separator, making my price look like

1.234,89

Can I do this solely with my XML formatting string or do I have to do the formatting in the java code (my ViewModel)?

like image 268
fweigl Avatar asked Jun 07 '16 08:06

fweigl


People also ask

Which is better Viewbinding and DataBinding?

Note: In many cases, view binding can provide the same benefits as data binding with simpler implementation and better performance. If you are using data binding primarily to replace findViewById() calls, consider using view binding instead.

Can I use Viewbinding and data binding together?

View binding doesn't support layout variables or layout expressions, so it can't be used to declare dynamic UI content straight from XML layout files. View binding doesn't support two-way data binding.


1 Answers

Try this format string:

%,.2f $

According to your own findings:

Depending on the Locale of the device (in this case, German ), the desired formatting should be automatically applied.

For German locale, this would be 1.234,89 $ whereas for UK, it would be 1,234.89 &

like image 108
kha Avatar answered Nov 15 '22 17:11

kha