kirtan403
kirtan403

Reputation: 7421

How to display formatted amounts in TextView?

I have a currency symbol in String and an amount in double. Till now I am showing amounts like this:

amount.setText(currency + " " + amount);

And at some places I have 2 TextViews to display amount with padding in between:

currency.setText(currency);
amount.setText(amount);

Which is fine. But, I am moving this code to the layout files with android data-binding and is there an easy way to format and show amounts in android?

Like symbol[space]amount where amount should be formatted with 2 decimal points if present, else whole number. For example, 100 will be displayed as 100, and not 100.00, but 123.2 will be displayed as 123.20 along with the currency symbol at first ($ 123.20, $ 100).

I know there are several ways(resource string format, NumberFormat) I can do that(I have not yet used any of them, just heard of them), but what will be the easiest and cleanest way to do this?

I am trying to find and convert all the 2 text views to single one and finding unified way to format and display amounts.

Thank you.

Upvotes: 7

Views: 10944

Answers (7)

masoud Cheragee
masoud Cheragee

Reputation: 359

do it like this

int enduser=35000000;
TextView lblEnduser=(TextView)v.findViewById(R.id.lblEnduser);
lblEnduser.setText(String.format("%,.0f", Float.valueOf(enduser) ));

output : 35,000,000

Upvotes: 0

qinmiao
qinmiao

Reputation: 5789

Maybe it's useful:MultiSizeTextView

<com.github.captain_miao.multisizetextview.MultiSizeTextView
    android:id="@+id/multi_text_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"

    app:beforeText="@string/before_text"
    app:beforeTextColor="@color/red"
    app:beforeTextSize="@dimen/text_size_small"
    app:beforeTextStyle="bold"

    app:centerText="@string/app_name"
    app:centerTextColor="@color/gray"
    app:centerTextSize="@dimen/text_size_big"

    app:afterText="@string/after_text"
    app:afterTextColor="@color/blue"
    app:afterTextSize="@dimen/text_size_small"
    app:afterTextStyle="bold"
    />

enter image description here

Upvotes: 1

kirtan403
kirtan403

Reputation: 7421

Inspired by the @Nowshad's answer, I can do that without external lib with data-binding library.

Provide currency and amount in layout files whenever required:

          <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="end"
                android:textAppearance="@style/TextAppearance.AppCompat.Large"
                app:amount="@{amount}"
                app:currency="@{currency}" />

And provide a binding adapter:

@BindingAdapter({"currency", "amount"})
    public static void setCurrencyAndAmount(TextView textView, String currency, double amount) {
        SpannableString spannableString = new SpannableString(currency + " " +
                new DecimalFormat("#.##").format(amount));

        spannableString.setSpan(new RelativeSizeSpan(0.6f), 0, 1, 0);

        textView.setText(spannableString);
    }

Simple and efficient.

Upvotes: 5

Long Ranger
Long Ranger

Reputation: 6008

If you are looking for some simple and easy way to format the string and set it to the TextView.

For the popular methods, follows this Android, Is it possible to format textview like System.out.format("%02d", n);?

If you are going to use DataBinding, you need to setup your own binding method since the origin android:text attributes are Integer(String resource) or String(Text).

In the Android official, you can use something like that (https://developer.android.com/topic/libraries/data-binding/index.html#expression_language)

android:text="@{@string/nameFormat(firstName, lastName)}"
android:text="@{@plurals/banana(bananaCount)}"

But if you want it in a more flexible way, you need to write up your own binding methods like the following.

In you code,

 @BindingAdapter(value = {"android:text", "android:formatArgs"}, requireAll = false)
    public static void bindTextStr(TextView tv, String text, Object[] formatstr) {
        if (formatstr == null) {
            tv.setText(text);
        } else {
            tv.setText(String.format(text, formatstr));
        }
    }

In your layout xml,

<variable
            name="normalStr"
            type="java.lang.String"/>
        <variable name="data" type="Object[]"/>
...
<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@{normalStr}"
        android:formatArgs="@{data}"
        />

In the Activity code,

    mBinding = DataBindingUtil.inflate(LayoutInflater.from(this), R.layout.activity_main, null, false);
    mBinding.setNormalStr("Data : 1(%s), 2(%d)");
    mBinding.setData(new Object[]{"Hello World",12345});

Upvotes: 1

sushildlh
sushildlh

Reputation: 9056

If you are using this amount.setText(currency + " " + amount); than every time when you use text.getText() you have to do separate the $ and space from the textView for geeting the actual amount .

BUT

In 2 textView you do not have to perform any operation for getText() method you directly get amount .

use this for 2 deciaml digit number and 0 decimal digit number...

 double price=23.1000;
 int number=(int)((price*100)%100);
 yourTextView.setText(number==0?new DecimalFormat("0").format(price):new DecimalFormat("0.00").format(price));

outPut:-

23.1000 -------> 23.10

23.0007 -------> 23

The above code is working .....

Note:- In the above 2, i suggest go with the 2 textView. That is so simple .

Upvotes: 1

ben10
ben10

Reputation: 190

amount.setText(currency + String.format("%.2f", amount));

Upvotes: 0

Nowshad
Nowshad

Reputation: 294

i think you need to look out some libraries you will find some good examples here is i recommending you one of best library for currency text data binding i use it its very helpful for me its save my code line here is the MoneyTextView

<org.fabiomsr.moneytextview.MoneyTextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="32dp"
    app:symbol="$"
    app:symbolGravity="start|top"
    app:symbolTextSize="30sp"
    app:symbolMargin="6dp"
    app:amount="1256.56"
    app:baseTextSize="54sp"
    app:decimalDigitsTextSize="30sp"
    app:decimalMargin="6dp"
    app:includeDecimalSeparator="false"
    app:baseTextColor="#FBFFE3"/>

Upvotes: 1

Related Questions