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;
}
Related
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;
}
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())));
}
I'm using google volley to retrieve source code from website. Some looping was done to capture the value in the code. I've successfully captured the data I wanted, but error was shown: NumberFormatException: Invalid float: "2,459.00"
My intention was to store the value after the class=ListPrice>
Sample:
RM 2,899.00
The example value of the source code I wanted to save is "RM2,459.00 "
Below is the code I've written:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lazada_result);
lelongResult = (TextView) findViewById(R.id.lelong_result);
RequestQueue lelong = MyVolley.getRequestQueue(this);
StringRequest myLel = new StringRequest(
Method.GET,
"http://list.lelong.com.my/Auc/List/List.asp?DA=A&TheKeyword=iphone&x=0&y=0&CategoryID=&PriceLBound=&PriceUBound=",
RetrieveLelong(), createMyReqErrorListener());
lelong.add(myLel);
}
private Response.Listener<String> RetrieveLelong() {
return new Response.Listener<String>() {
#Override
public void onResponse(String response) {
ArrayList<Float> integers = new ArrayList<>();
String to = "class=ListPrice>";
String remainingText = response;
String showP = "";
while (remainingText.indexOf(to) >= 0) {
String tokenString = remainingText.substring(remainingText
.indexOf(to) + to.length());
String priceString = tokenString.substring(0,
tokenString.indexOf("<"));
float price = Float.parseFloat(priceString.replaceAll("[^\\d,]+", "").trim());
integers.add((price / 100));
remainingText = tokenString;
}
for (int i = 0; i < integers.size(); i++) {
String test1 = Float.toString(integers.get(i));
showP += test1 + "\n";
}
lelongResult.setText(showP);
}
};
}
The problem was as below:
I've tried all sort of replaceAll(),
1)replaceAll("[^\d,]+","") result:2,89900
replace all character except digits and comma works.
2)replaceAll("[^\d]+","") result:Invalid int""
replace all character include comma and dot ,not working
3)replaceAll("[^\d.]+,"") result:Invalid int""
replace all character exclude digits and dot, not working
From the experiment 2&3 coding above,I've noticed that if the comma were removed,i cant parseFloat as the value received by it is: "".NumberFormatException:Invalid Float:"" shown.
From the experiment 1,NumberFormatException:Invalid Float "2,45900" is showned.
The problem was replacing comma ,the code will not work but with the presence of comma ,the value cannot be stored into string
try this:
float price = Float.parseFloat(priceString.replaceAll("RM", "").trim());
use `replaceAll(Pattern.quote(","), "");
EDIT
if you want only numbers then use this
String s1= s.replaceAll("\D+","");
Try to parse the number by specifying the Locale.
NumberFormat format = NumberFormat.getInstance(Locale.KOREAN);
Number number = format.parse(priceString.replaceAll("RM", ""));
double d = number.doubleValue();
I'm just guessing the locale, don't know what you should use, depends on country
You need to do it one by one
priceString=priceString.replaceAll("\\D", "");
priceString=priceString.replaceAll("\\s", "");
now
priceString=priceString.trim();
float price = Float.parseFloat(priceString);
the problem is that in your code:
priceString.replaceAll(Pattern.quote(","), "");
float price = Float.parseFloat(priceString.replaceAll("\\D+\\s+", "").trim());
You are replacing coma but not storing the value!
you have to do:
priceString = priceString.replaceAll(",", "");
float price = Float.parseFloat(priceString.replaceAll("\\D+\\s+", "").trim());
I'm not sure of the pattern "\D+\s" because if you remove the coma you don't need to replace anything else (except "RM" that i assume you already removed)
Update: set locale and parse a number:
NumberFormat format = NumberFormat.getInstance(Locale.KOREAN);
Number number = format.parse(priceString.replaceAll("RM", ""));
double d = number.doubleValue();
Is there way to convert a string to double. This is how i did.
String s = b.getText().toString();
double d = Double.parseDouble(s);
It gives NumberFormatException
Try this
String s = b.getText().toString();
double d = Double.valueOf(s.trim()).doubleValue();
You are probably starting off with a zero-length string. Check the length before you parse it. It also wouldn't hurt to catch NumberFormatException, although that shouldn't be problem if you have android:inputType="number" in the view's layout.
double d = 0;
CharSequence cs = b.getText();
if(cs != null && cs.length() > 0) {
d = Double.parseDouble(cs.toString());
}
i have a similar problem.
for correct formatting EditText text content to double value i use this code:
try {
String eAm = etAmount.getText().toString();
DecimalFormat dF = new DecimalFormat("0.00");
Number num = dF.parse(eAm);
mPayContext.amount = num.doubleValue();
} catch (Exception e) {
mPayContext.amount = 0.0d;
}
this is independet from current phone locale and return correct double value.
hope it's help;
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);
}