nazanin
nazanin

Reputation: 749

How can I convert numbers to currency format in android

I want to show my numbers in money format and separate digits like the example below:

1000 -----> 1,000

10000 -----> 10,000

100000 -----> 100,000

1000000 -----> 1,000,000

Thanks

Upvotes: 67

Views: 100891

Answers (19)

John De la cruz
John De la cruz

Reputation: 96

fun formatToCurrency(editText: EditText) {
editText.addTextChangedListener(object : TextWatcher {
    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}

    override fun afterTextChanged(s: Editable?) {
        try {
            // Remove any non-numeric characters
            val cleanString = s.toString().replace(Regex("[^\\d]"), "")

            val parsed = cleanString.toDouble()
            val formatted = NumberFormat.getCurrencyInstance(Locale.US).format(parsed / 100)

            // Update the EditText with the formatted currency
            editText.removeTextChangedListener(this)
            editText.setText(formatted)
            editText.setSelection(formatted.length)
            editText.addTextChangedListener(this)
        } catch (ex: NumberFormatException) {
            ex.printStackTrace()
        }
    }
})}

Upvotes: 0

OgabekDev
OgabekDev

Reputation: 271

One another helpful extension function

fun Long.moneyType(): String {
    val s = this.toString()
    var result: String = s[s.length - 1].toString()
    for (i in 1 until s.length) {
        result = if (i % 3 == 0) {
            "${s[s.length - i - 1]} $result"
        } else {
            s[s.length - i - 1] + result
        }
    }
    return "$result USD"
}

You can also use Int as a parent of extention.

There is an updated version of the code

fun String.moneyType(): String {
    return this
        .reversed()
        .chunked(3)
        .joinToString(" ")
        .reversed()
}

To use this you can take another extension function

fun Long.moneyType(): String {
    return this.toString().moneyType() + " USD"
}

everthing is ready to use. Good luck

Upvotes: 2

Damercy
Damercy

Reputation: 1055

Updated 2022 answer

Try this snippet. It formats a number in string complete with the currency & setting fractional digits.

/**
     * Formats amount in string to human-readable amount (separated with commas
     * & prepends currency symbol)
     *
     * @param amount The amount to format in String
     * @return The formatted amount complete with separators & currency symbol added
     */
    public static String formatCurrency(String amount) {
        String formattedAmount = amount;
        try {
            if (amount == null || amount.isEmpty())
                throw new Exception("Amount is null/empty");
            Double amountInDouble = Double.parseDouble(amount);
            NumberFormat numberFormat = NumberFormat.getCurrencyInstance(new Locale("en", "IN"));
            numberFormat.setMaximumFractionDigits(2);
            numberFormat.setMinimumFractionDigits(2);
            formattedAmount = numberFormat.format(amountInDouble);
        } catch (Exception exception) {
            exception.printStackTrace();
            return formattedAmount;
        }
        return formattedAmount;
    }

Upvotes: 4

Mado
Mado

Reputation: 461

here is a kotlin version to Format Currency, here i'm getting an argument from another fragment from an input Field then it will be set in the textView in the main Fragment

fun formatArgumentCurrency(argument : String, textView: TextView) {

        val valueText = requireArguments().get(argument).toString()
        val dec = DecimalFormat("#,###.##")
        val number = java.lang.Double.valueOf(valueText)
        val value = dec.format(number)
        val currency = Currency.getInstance("USD")
        val symbol = currency.symbol
        textView.text = String.format("$symbol$value","%.2f" )

    }

Upvotes: -1

DavidUps
DavidUps

Reputation: 420

NumberFormat.getCurrencyInstance(Locale("ES", "es")).format(number)

Upvotes: -1

abdulwasey20
abdulwasey20

Reputation: 837

If you have the value stored in a String like me, which was coming from the server like "$20000.00". You can do something like this in Kotlin (JetpackCompose):

@Composable
fun PrizeAmount(
    modifier: Modifier = Modifier,
    prize: String,
) 
{
    val currencyFormat = NumberFormat.getCurrencyInstance(Locale("en", "US"))
    val text = currencyFormat.format(prize.substringAfter("$").toDouble())
    ...
}

Output: "$20,000.00"

Upvotes: 0

sadat
sadat

Reputation: 4342

private val currencyFormatter = NumberFormat.getCurrencyInstance(LOCALE_AUS).configure()

private fun NumberFormat.configure() = apply {
    maximumFractionDigits = 2
    minimumFractionDigits = 2
}

fun Number.asCurrency(): String {
    return currencyFormatter.format(this)
}

And then just use as

val x = 100000.234
x.asCurrency()

Upvotes: 2

mikail yusuf
mikail yusuf

Reputation: 337

Here's a kotlin Extension that converts a Double to a Currency(Nigerian Naira)

fun Double.toRidePrice():String{
    val format: NumberFormat = NumberFormat.getCurrencyInstance()
    format.maximumFractionDigits = 0
    format.currency = Currency.getInstance("NGN")

    return format.format(this.roundToInt())
}

Upvotes: 6

Jaya Prakash
Jaya Prakash

Reputation: 559

You can easily achieve this with this small simple library. https://github.com/jpvs0101/Currencyfy

Just pass any number, then it will return formatted string, just like that.

currencyfy (500000.78); // $ 500,000.78  //default

currencyfy (500000.78, false); // $ 500,001 // hide fraction (will round off automatically!)

currencyfy (500000.78, false, false); // 500,001 // hide fraction & currency symbol

currencyfy (new Locale("en", "in"), 500000.78); // ₹ 5,00,000.78 // custom locale

It compatible with all versions of Android including older versions!

Upvotes: -1

Thomas Mary
Thomas Mary

Reputation: 1579

Another approach :

NumberFormat format = NumberFormat.getCurrencyInstance();
format.setMaximumFractionDigits(0);
format.setCurrency(Currency.getInstance("EUR"));

format.format(1000000);

This way, it's displaying 1 000 000 € or 1,000,000 €, depending on device currency's display settings

Upvotes: 83

AbhinayMe
AbhinayMe

Reputation: 2547

double number = 1000000000.0;
String COUNTRY = "US";
String LANGUAGE = "en";
String str = NumberFormat.getCurrencyInstance(new Locale(LANGUAGE, COUNTRY)).format(number);

//str = $1,000,000,000.00

Upvotes: 23

M.A.R
M.A.R

Reputation: 97

i used this code for my project and it works:

   EditText edt_account_amount = findViewById(R.id.edt_account_amount);
   edt_account_amount.addTextChangedListener(new DigitFormatWatcher(edt_account_amount));

and defined class:

    public class NDigitCardFormatWatcher implements TextWatcher {

EditText et_filed;

String processed = "";


public NDigitCardFormatWatcher(EditText et_filed) {
    this.et_filed = et_filed;
}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {

}

@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {

}

@Override
public void afterTextChanged(Editable editable) {

    String initial = editable.toString();

    if (et_filed == null) return;
    if (initial.isEmpty()) return;
    String cleanString = initial.replace(",", "");

    NumberFormat formatter = new DecimalFormat("#,###");

    double myNumber = new Double(cleanString);

    processed = formatter.format(myNumber);

    //Remove the listener
    et_filed.removeTextChangedListener(this);

    //Assign processed text
    et_filed.setText(processed);

    try {
        et_filed.setSelection(processed.length());
    } catch (Exception e) {
        // TODO: handle exception
    }

    //Give back the listener
    et_filed.addTextChangedListener(this);

}

}

Upvotes: 2

Alireza Noorali
Alireza Noorali

Reputation: 3265

This Method gives you the exact output which you need:

public String currencyFormatter(String num) {
    double m = Double.parseDouble(num);
    DecimalFormat formatter = new DecimalFormat("###,###,###");
    return formatter.format(m);
}

Upvotes: 8

Samet ÖZTOPRAK
Samet ÖZTOPRAK

Reputation: 3366

Currency formatter.

    public static String currencyFormat(String amount) {
        DecimalFormat formatter = new DecimalFormat("###,###,##0.00");
        return formatter.format(Double.parseDouble(amount));
    }

Upvotes: 17

Mohammad Zarei
Mohammad Zarei

Reputation: 1802

The way that I do this in our app is this:

amount.addTextChangedListener(new CurrencyTextWatcher(amount));

And the CurrencyTextWatcher is this:

public class CurrencyTextWatcher implements TextWatcher {

private EditText ed;
private String lastText;
private boolean bDel = false;
private boolean bInsert = false;
private int pos;

public CurrencyTextWatcher(EditText ed) {
    this.ed = ed;
}

public static String getStringWithSeparator(long value) {
    DecimalFormat formatter = (DecimalFormat) NumberFormat.getNumberInstance(Locale.US);
    String f = formatter.format(value);
    return f;
}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
    bDel = false;
    bInsert = false;
    if (before == 1 && count == 0) {
        bDel = true;
        pos = start;
    } else if (before == 0 && count == 1) {
        bInsert = true;
        pos = start;
    }
}

@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    lastText = s.toString();
}

@Override
public void afterTextChanged(Editable s) {
    ed.removeTextChangedListener(this);
    StringBuilder sb = new StringBuilder();
    String text = s.toString();
    for (int i = 0; i < text.length(); i++) {
        if ((text.charAt(i) >= 0x30 && text.charAt(i) <= 0x39) || text.charAt(i) == '.' || text.charAt(i) == ',')
            sb.append(text.charAt(i));
    }
    if (!sb.toString().equals(s.toString())) {
        bDel = bInsert = false;
    }
    String newText = getFormattedString(sb.toString());
    s.clear();
    s.append(newText);
    ed.addTextChangedListener(this);

    if (bDel) {
        int idx = pos;
        if (lastText.length() - 1 > newText.length())
            idx--; // if one , is removed
        if (idx < 0)
            idx = 0;
        ed.setSelection(idx);
    } else if (bInsert) {
        int idx = pos + 1;
        if (lastText.length() + 1 < newText.length())
            idx++; // if one , is added
        if (idx > newText.length())
            idx = newText.length();
        ed.setSelection(idx);
    }
}

private String getFormattedString(String text) {
    String res = "";
    try {
        String temp = text.replace(",", "");
        long part1;
        String part2 = "";
        int dotIndex = temp.indexOf(".");
        if (dotIndex >= 0) {
            part1 = Long.parseLong(temp.substring(0, dotIndex));
            if (dotIndex + 1 <= temp.length()) {
                part2 = temp.substring(dotIndex + 1).trim().replace(".", "").replace(",", "");
            }
        } else
            part1 = Long.parseLong(temp);

        res = getStringWithSeparator(part1);
        if (part2.length() > 0)
            res += "." + part2;
        else if (dotIndex >= 0)
            res += ".";
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return res;
}

Now if you add this watcher to your EditText, as soon as user enter his number, the watcher decides whether it needs separator or not.

Upvotes: 2

Hemil Kumbhani
Hemil Kumbhani

Reputation: 349

Try the following solution:

NumberFormat format = NumberFormat.getCurrencyInstance();
((TextView)findViewById(R.id.text_result)).setText(format.format(result));

The class will return a formatter for the device default currency.

You can refer to this link for more information:

https://developer.android.com/reference/java/text/NumberFormat.html

Upvotes: 7

Valentun
Valentun

Reputation: 1711

Use this:

int number = 1000000000;
String str = NumberFormat.getNumberInstance(Locale.US).format(number);
//str = 1,000,000,000

Upvotes: 12

Kavach Chandra
Kavach Chandra

Reputation: 770

Use a Formatter class For eg:

String s = (String.format("%,d", 1000000)).replace(',', ' ');

Look into: http://developer.android.com/reference/java/util/Formatter.html

Upvotes: 3

dFrancisco
dFrancisco

Reputation: 934

You need to use a number formatter, like so:

NumberFormat formatter = new DecimalFormat("#,###");
double myNumber = 1000000;
String formattedNumber = formatter.format(myNumber);
//formattedNumber is equal to 1,000,000

Hope this helps!

Upvotes: 50

Related Questions