Android String format - price - android

Is there an easy formatter to format my String as a price?
So my string is: 300000 i'd like to "300 000" with space
or 1000000 "1 000 000"
Leslie

This does it:
String s = (String.format("%,d", 1000000)).replace(',', ' ');

Use Formatter class to format string
format("%,d", 1024);
After that replace , with space.
http://developer.android.com/reference/java/util/Formatter.html

You cannot do this with a simple format string but with the DecimalFormat and DecimalFormatSymbols class.
int value = 123456789;
DecimalFormat fmt = new DecimalFormat();
DecimalFormatSymbols fmts = new DecimalFormatSymbols();
fmts.setGroupingSeparator(' ');
fmt.setGroupingSize(3);
fmt.setGroupingUsed(true);
fmt.setDecimalFormatSymbols(fmts);
TextView txt = (TextView) findViewById(R.id.txt);
txt.setText(fmt.format(value));
There are lots and lots of other options in these classes. For example you could seperate the numbers with dots or commas or use a locale specific setting.
For example you can use the fmt.setCurrency method:
fmt.setCurrency(Currency.getInstance(Locale.GERMANY));

double yourPrice = 1999999.99;
String formattedPrice = new DecimalFormat("##,##0.00€").format(yourPrice);
output :
formattedPrice = 1.999.99,99€

if you have integer value, most elegant in my opinion
public static String formatNumberWithSpaces(long number) {
DecimalFormat formatter = (DecimalFormat) NumberFormat.getInstance();
DecimalFormatSymbols symbols = formatter.getDecimalFormatSymbols();
symbols.setGroupingSeparator(' ');
return formatter.format(number);
}

Related

Android - Decimal Formatter

I've try this in my device and work fine. But, in some Android device, the symbol is in wrong place. This is my code :
public static String convertToRupiah(String priceBeforeConverted){
//manual setting separator, because currently RUPIAH is NOT supported
DecimalFormat formatter = (DecimalFormat) DecimalFormat.getCurrencyInstance();
DecimalFormatSymbols formatRupiah = new DecimalFormatSymbols();
formatRupiah.setCurrencySymbol("Rp ");
formatRupiah.setMonetaryDecimalSeparator(',');
formatRupiah.setGroupingSeparator('.');
formatter.setDecimalFormatSymbols(formatRupiah);
Double price = StringFormatter.isNullOrEmpty(priceBeforeConverted) ? 0.00 : Double.valueOf(priceBeforeConverted) ;
String conversionResult = formatter.format(price);
if(conversionResult.endsWith(",00"))
conversionResult = conversionResult.substring(0, conversionResult.length()-3);
return conversionResult;
}
expected result is : Rp 25.000,00
String pattern = "Rp ###,###.000 ";
DecimalFormat decimalFormat = new DecimalFormat(pattern);
String format = decimalFormat.format(25.000);
System.out.println(format);
--Try this, your zeros after decimal place will not miss. Output of this code is.
Rp 25.000
Let me know if anything is not clear.

Converting Exponential value to Decimal Android

I have a String in the format of "6.151536E-8"
How can i convert it to a string or int as 0.000000061 ?
Use this if you want to have just 2 significant digits:
String str = "6.151536E-8";
BigDecimal bd = new BigDecimal(str);
bd = bd.round(new MathContext(2, RoundingMode.HALF_UP));
System.out.println(bd.toPlainString());
This prints: 0.000000062
If you want to round down to 0.000000061 then use RoundingMode.DOWN

android to add comma for the numbers which are in String

I'm getting a string from Json response as follows:
"Your account balance is 100000 as on Monday"
In this I need to add comma to the numerical value. Can anyone please help me how I can add this.Thanks in advance.
In this case, I would like to have the output in the following format:
"Your account balance is 100,000 as on Monday"
NumberFormat anotherFormat = NumberFormat.getNumberInstance(Locale.US);
if (anotherFormat instanceof DecimalFormat) {
DecimalFormat anotherDFormat = (DecimalFormat) anotherFormat;
anotherDFormat.applyPattern("#.00");
anotherDFormat.setGroupingUsed(true);
anotherDFormat.setGroupingSize(3);
for (double d : numbers) {
System.out.println(anotherDFormat.format(d));
}
}
final String jsonString = "Your account balance is 100000 as on Monday";
DecimalFormat decFormat = (DecimalFormat) NumberFormat.getNumberInstance(Locale.US);
decFormat.setGroupingUsed(true);
decFormat.setGroupingSize(3);
Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher(jsonString);
while (m.find()) {
System.out.println(decFormat.format(Double.valueOf(m.group())));
}

replace (,) in place of (.) in textview in android

I am using this code to add two number after (. in my number. For example: I have string 14.3, so I want to get 14.30, when get 14 I want to get 14.00. This is code:
NumberFormat format = NumberFormat.getNumberInstance();
format.setMinimumFractionDigits(2);
format.setMaximumFractionDigits(2);
tvPrice.setText(addDolar(format.format(Double.parseDouble(alerts.getPrice()))));
private String addDolar(String amount) {
if(amount.startsWith("-")) {
return "-$ "+amount.substring(1, amount.length());
}
else
return "$ "+amount;
}
problem is that I want to get '.' and now i get ','.
You can replace it:
someDouble.toString().replace(",", "."))
If you want to add two precisions only, then try this code
DecimalFormat format = new DecimalFormat("##.##");
String formatted = format.format(your_value);
editText.setText(formatted);
Use this function :
public double round(double unrounded)
{
BigDecimal bd = new BigDecimal(unrounded);
BigDecimal rounded = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
return rounded.doubleValue();
}
Try following
NumberFormat format = NumberFormat.getNumberInstance();
format.setMinimumFractionDigits(2);
format.setMaximumFractionDigits(2);
tvPrice.setText(addDolar(format.format(Double.parseDouble(alerts.getPrice()))));
private String addDolar(String amount)
{
amount = amount.replace ( ",","." ); // Add this line
if(amount.startsWith("-"))
{
return "-$ "+amount.substring(1, amount.length());
}
else
return "$ "+amount;
}

Decimal point or decimal comma in Android

Is there an easy way to read back if the language set uses a decimal comma or a decimal point?
EDIT: Updating based on #Algar's suggestion; you can directly use:
char separatorChar = DecimalFormatSymbols.getInstance().getDecimalSeparator();
As it will always return an instance of DecimalFormatSymbols.
NumberFormat nf = NumberFormat.getInstance();
if (nf instanceof DecimalFormat) {
DecimalFormatSymbols sym = ((DecimalFormat) nf).getDecimalFormatSymbols();
char decSeparator = sym.getDecimalSeparator();
}
Docs:
NumberFormat, DecimalFormat, DecimalFormatSymbols
According to the DecimalFormat docs, apparently calling NumberFormat.getInstance() is safe, but may return a subclass other than DecimalFormat (the other option I see is ChoiceFormat). I believe for the majority of instances it should be a DecimalFormat, and then you can compare decSeparator against a , and . to see which format it is using.
Or why not
DecimalFormatSymbols.getInstance().decimalSeparator
I did try this and it worked fine...
String osVersion = System.getProperty("os.version");
String PhoneModel = android.os.Build.MODEL;
String locale = this.getResources().getConfiguration().locale.getDisplayCountry();
char decSeparator = '*';
DecimalFormatSymbols dfs = new DecimalFormatSymbols();
decSeparator = dfs.getDecimalSeparator();
String androidVersion = android.os.Build.VERSION.RELEASE;
String prologue = String.format("OS verson = %s PhoneModel = %s locale = %s DecimalFormatSymbol = [%c] androidVersion = %s ",
osVersion ,PhoneModel, locale, decSeparator,androidVersion);
you can use:
Currency currency = Currency.getInstance(device_locale);
than use currency.getSymbol() for symbol. For default device locale you can use:
#TargetApi(Build.VERSION_CODES.N)
public static Locale getCurrentLocale(Context c) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return c.getResources().getConfiguration().getLocales().get(0);
} else {
//noinspection deprecation
return c.getResources().getConfiguration().locale;
}
}
Not sure if there is an easy way, but you could test which language set is being used and then make the appropriate changes according to if that language used commas or decimals.

Categories

Resources