For what function I can use in android to display the number into different formats.
For eg: If I enter 1000 then it should display like this 1,000. If I enter 1000
You could use DecimalFormat
and just format the number
DecimalFormat formatter = new DecimalFormat("#,###,###");
String yourFormattedString = formatter.format(100000);
The result will be
1,000,000
for 100000010,000
for 100001,000
for 1000Update 12/02/2019
This String.format("%,d", number)
would be a better(less hardcoded) solution as indicated in the comments below by @DreaminginCode so I thought I would add it here as an alternative
Add a text change listener as below (Also make sure that the input type selected for Edittext is Number) :
etTest.addTextChangedListener(new TextWatcher() {
boolean isManualChange = false;
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
if (isManualChange) {
isManualChange = false;
return;
}
try {
String value = s.toString().replace(",", "");
String reverseValue = new StringBuilder(value).reverse()
.toString();
StringBuilder finalValue = new StringBuilder();
for (int i = 1; i <= reverseValue.length(); i++) {
char val = reverseValue.charAt(i - 1);
finalValue.append(val);
if (i % 3 == 0 && i != reverseValue.length() && i > 0) {
finalValue.append(",");
}
}
isManualChange = true;
etTest.setText(finalValue.reverse());
etTest.setSelection(finalValue.length());
} catch (Exception e) {
// Do nothing since not a number
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
public static String formatNumber(int number){
return NumberFormat.getNumberInstance(Locale.getDefault()).format(number);
}
public static String formatNumber(String number){
return NumberFormat.getNumberInstance(Locale.getDefault()).format(Integer.parseInt(number));
}
private String getFormatedAmount(int amount){
return NumberFormat.getNumberInstance(Locale.US).format(amount);
}
try this one hope it will help.
System.out.println(NumberFormat.getNumberInstance(Locale.US).format(1000));
You can use Numberformat
public static double getNumberByString(String s) throws ParseException {
return NumberFormat.getInstance(Locale.getDefault()).parse(s).doubleValue();
}