I have a method that converts numeric values to a formatted string. It works well, but only on versions less than android 7. On Android 7 and above it is ignored.
public static String printableSumSeparators(double sum, String format) {
DecimalFormatSymbols dfSymbols = new DecimalFormatSymbols();
dfSymbols.setDecimalSeparator(COMMA_SEPARATOR);
dfSymbols.setGroupingSeparator(' ');
DecimalFormat df = new DecimalFormat(format, dfSymbols);
df.setGroupingUsed(true);
return df.format(sum);
}
Where COMMA_SEPARATOR = ',';
The input of the method is fed with 2 parameters, the number itself for the conversion and the format in the form: ##.0#
Example:
Input: 500000
Output: 500 000
But on the android 7 it does not work and the number is not formatted
Question: How to fix this bug and make it work on the latest version of android
On the latest versions of android you also need to setGroupingSize. Like this:
DecimalFormatSymbols dfSymbols = new DecimalFormatSymbols();
dfSymbols.setDecimalSeparator(',');
dfSymbols.setGroupingSeparator(' ');
DecimalFormat df = new DecimalFormat(format, dfSymbols);
df.setGroupingSize(3);
df.setGroupingUsed(true);
Maybe below code is useful for you, because its work like separating the decimal value using comma's.
protected String getCommaSeparated(String s)
{
try
{
if (s.length() > 0)
{
s =
customFormat("##,##,##0",Double.parseDouble(s.toString().replace(",","")));
if(s.length() > 0)
{
return s;
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
return s;
}
public String customFormat(String pattern, double value)
{
DecimalFormat myFormatter = new DecimalFormat(pattern);
String output = myFormatter.format(value);
return output;
}
Related
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.
I need to pass a fare amount to the payment gateway. It was working good in English language setting. While I changed the language into Burmese it changes like this 000000၁၀၀၀၀၀, so I am getting invalid amount.Even I have set currency as Locale.English.But didnt work it.
Your answer is more appreciated!!!
try {
NumberFormat nf = NumberFormat.getInstance(Locale.ENGLISH);
return nf.parse(s).doubleValue();
} catch (java.text.ParseException e) {
e.printStackTrace();
return 0.0;
}
You can do like this,
//calling of method
String your_amount= setCurrencyFormat(your_string);
private String setCurrencyFormat(String amt) {
if (amt.equals("null") || amt.equals("")) {
amt = "0";
}
double amount = Double.parseDouble(amt);
//here i have done it for Indian currency i.e "in" you can opt for other countries currency
Format formatter = NumberFormat.getCurrencyInstance(new Locale("en", "in"));
return formatter.format(amount);
}
Note: I get my amount in string format you can covert you amt to string if it is in integer format
// above onCreate
private DecimalFormat decimalFormat =(DecimalFormat)
NumberFormat.getInstance();
// inside my textWatcher
String[] splitted = originalString.split("((?<=[-+x÷])|(?=[-+.x÷]))");
StringBuilder formatted = new StringBuilder();
for (String word : splitted) {
try {
BigInteger num = new BigInteger(word);
formatted.append(decimalFormat.format(num));
} catch (NumberFormatException e) {
formatted.append(word);
}
}
I have taken a number as a string variable and wanted to show with thousand separator like 2345678 as 23,45,678 when i am using in Nepali language. Badly the code works like this २,३४५,६७८ for 2345678.
Amazingly this works for Hindi Language as a system locale and can show 23,45,678. Why not for Nepali Language ??
try this code:
<NumberFormat thousandSeperator="." decimalSeperator="," onKeyDown = {(e) =>
{
const {key, target} = e;
const {selectionStart, value} = target;
if (key === '.') {
e.preventDefault();
target.value = `${value.substr(0,
selectionStart)},${value.substr(selectionStart, value.length)}`;
}
}}/>
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;
}
I have problem with finding phone number in string.
I have function:
public void getPhoneNumber()
{
Pattern intsOnly = Pattern.compile("\\d+");
Matcher makeMatch = intsOnly.matcher(number);
makeMatch.find();
String result = makeMatch.group();
Log.i("Pattern", result);
}
But I have bad result.
My string:
String number = "String string s. s. str. 23-232 12 23 adsdsa"
Is your number always in the format 23-232 12 23?. If so you can try the below.
Try the below
String s="String string s. s. str. 23-232 12 23 adsdsa";
Pattern p = Pattern.compile("[0-9]{2}[-][0-9]{3}[ ][0-9]{2}[ ][0-9]{2} ");
// match 2 numbers followed by -,
// match 3 numbers followed by space.
// match 2 numbers followed by space.
// match 2 numbers followed by space.
Matcher m = p.matcher(s);
if(m.find()) {
System.out.println("............"+m.group(0));
}
Edit:
Pattern p = Pattern.compile("(\\([0-9]{2}\\)|[0-9]{2})[ ][0-9]{3}[ ][0-9]{2,2}[ ][0-9]{2} ");
Use a or operator match (23) or 23
You can also remove the rounded brackets by using the replace method
String s="String string s. s. str. (23) 232 32 34 11111adsds0000000000000000a0";
String r = s.replace("(","");
String r2= r.replace(")", "");
System.out.println(r2);
//String string s. s. str. 23 232 32 34 11111adsds0000000000000000a0
Try using regex, similiar question here: Link
String value = string.replaceAll("[^0-9]","");
I wrote this:
This solved my problem :)
public String getPhoneNumber()
{
char[] temp = numer.toCharArray();
String value="";
int licz=0;
for(int i=0;i<temp.length;i++)
{
if(licz<9)
{
if(Character.toString(temp[i]).matches("[0-9]"))
{
value+=Character.toString(temp[i]);
licznik++;
}
else if(Character.toString(temp[i]).matches("\u0020|\\-|\\(|\\)"))
{
}
else
{
value="";
licz=0;
}
}
}
if(value.length()!=9)
{
value=null;
}
else
{
value="tel:"+value.trim();
}
return value;
}