I'm having trouble formatting this decimal value format (8487.0) for that format. "8.48".
I have tried the solution of other issues posted here but I did not succeed.
Example:
Double n1 = Double.parseDouble (String.valueOf (8487.0));
DecimalFormat dec = new DecimalFormat ("#. ##");
String credits = dec.format (n1); Log.d (TAG, "test" + credits);
Currently it has the output like this: 8487
Any help is welcomed, Thanks.
You can use String format
String answer = String.format("%.2f", (8487.0 / 1000));
Log.d(TAG, answer); //8.49
There are two cases; whether you want to round off or not. Here's the sample code for both the cases.
double d = 8487.0;
d /= 1000;
DecimalFormat f = new DecimalFormat("##.00");
f.setRoundingMode(RoundingMode.FLOOR);
String notRounded = f.format(d);
System.out.println("Not Rounded: " + notRounded);
f.setRoundingMode(RoundingMode.HALF_UP);
String rounded = f.format(d);
System.out.println("Rounded: " + rounded);
So, do you want to reduce the number by a factor 1000 ? e.g. g to kg ?
Double n1 = Double.parseDouble (String.valueOf (8487.0));
Double n2 = n1 / 1000;
DecimalFormat dec = new DecimalFormat ("#. ##");
String credits = dec.format(n2);
Log.d (TAG, "test" + credits);
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'm having a problem with Talkback. In my string I have the following number.
1,827
it's a Dutch number so the number means:
1 euro and 82,7 cents.
But Talkback is saying:
18 hundred and 27 euro.
So this problem only occurs when I have a number with more than 2 decimals. How to fix this issue?
---EDIT---
When I'm reading this page: https://english.stackexchange.com/questions/62397/reading-out-decimal-numbers-in-english
it seems I must pronounce the number 1,827 as the following:
one point eight two seven instead to act if it is a number. How to do this?
---EDIT---
I included the following:
StringTokenizer stringTokenizer = new StringTokenizer(value, ".");
String currencyBeforeComma = null;
String currencyAfterComma = null;
while (stringTokenizer.hasMoreTokens()) {
currencyBeforeComma = stringTokenizer.nextToken();
currencyAfterComma = stringTokenizer.nextToken();
}
result = currencyBeforeComma + " point " + currencyAfterComma;
So now its pronouncing: one point eighthunderd twentyseven. So this is still now what i want.
---EDIT---
String value = 1,827;
String result = "";
for (Character chars : value.toCharArray()) {
result = result + chars + " ";
}
String replace = result.replace(getResources().getString(R.string.accessibility_decimal_separator), getResources().getString(R.string.accessibility_decimal_separator_text));
return replace;
This is what i did. I created a whitespace for every char in the value string and for the , or . I replaced it with a comma or point text.
This works for now but it isn't a clean solution. If anybody else has a better solution, please share
Try this and modify your as per your requirement
TextView currencylbl = (TextView) findViewById(R.id.currencylbl);
boolean countryCurrency = true;
String currency = "1,827";
if(countryCurrency==true && currency.contains(",")){
StringTokenizer stringTokenizer = new StringTokenizer(currency, ",");
String currencyBeforeComma = null;
String currencyAfterComma = null;
while (stringTokenizer.hasMoreTokens()) {
currencyBeforeComma = stringTokenizer.nextToken();
currencyAfterComma = stringTokenizer.nextToken();
currencylbl.setText(currency);
}
Double double1 = Double.parseDouble(currencyAfterComma);
double1 = Double.parseDouble(currencyBeforeComma)+double1/1000;
currencylbl.setContentDescription(double1+"");
}
countryCurrency refers to particular Country currency boolean.
Also modify as per your requirement.
Double double1 = Double.parseDouble(currencyAfterComma);
double1 = Double.parseDouble(currencyBeforeComma)+double1/1000;
currencylbl.setContentDescription(double1+"");
xml is
<TextView
android:id="#+id/currencylbl"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24sp"
/>
I have a SQLDB with table of field REAL. In my layout I have set its field size to allow only 8+2 digits. In my object I have used the data-type of the field as "float".
qs[0] = "CREATE TABLE " + RELATION_TABLE_NAME + "(id TEXT PRIMARY KEY, name TEXT NOT NULL, startBal REAL NOT NULL, currentBal REAL NOT NULL);";
<EditText android:text="" android:id="#+id/relCurrBalTxt" style="#style/EditTextStyle"
android:inputType="numberDecimal" android:maxLength="11" android:hint="12345678.99" />
I entered value "87654321.99" in my editText and clicked save. It populates the object
// Send the data to object
rowData.setValue(2, Float.parseFloat(sbalTxt.getText().toString()));
// In object, this is how I save it
this.setCurrentBalance( ((Float)value).floatValue() ); // value is Object type
// Saving data in ContenteValues to save to DB
// LOG Rcvd from Object while Saving CurrBal: 8.765432E7
values.put("currentBal", new Float(rowData.getValue(3).toString()));
On saving, it directly show the table with the updated data. While showing it in table I use DecimalFormat to make sure it is shown in proper manner :
field_type = r.getFieldType(field);
// Get Data
str = r.getValue(field).toString();
// Format accordingly
if(field_type.equals(DBRow.DOUBLE_TYPE) || field_type.equals(DBRow.FLOAT_TYPE)) {
double douValue = Double.parseDouble(str);
//NumberFormat nf = NumberFormat.getNumberInstance(Locale.ITALY);
//DecimalFormat df = (DecimalFormat) nf;
DecimalFormat df = new DecimalFormat();
df.applyPattern("##,###,###.##");
df.setGroupingUsed(true);
str = df.format(douValue);
// Log.v("DF", "While Showing in Table : double = " + douValue + " String = " + str);
}
((TextView) tr.getChildAt(field)).setText(str);
HERE it showed me the value : 8.765432E7
When I again selected that row to see the values in EditText I see : 87654320.00
How is the value changed ? In other instance also I saved the data as "50009876.99", but somehow it doesn't save .99 and makes that as .00 i.e 50009876.00.
Why things are not working correctly ? Where am I going wrong ?
Any help is highly appreciated.
*EDIT : DecimalFromat code used to display in table *
// Format accordingly
if(field_type.equals(DBRow.DOUBLE_TYPE) || field_type.equals(DBRow.FLOAT_TYPE)) {
/*
WAS USING THIS CODE TILL NOW
DecimalFormatSymbols dfs = new DecimalFormatSymbols();
String decep = String.valueOf(dfs.getDecimalSeparator());
int index = str.indexOf(decSep);
if (index > 0) {
// If digits after decimal are more than 2
if (str.substring(index+1).length() > 2) {
str = str.substring(0, index+3);
}
}
DecimalFormat df = new DecimalFormat();
df.setGroupingUsed(true);
str = df.format(Double.parseDouble(str));
if (addRow)
create_addTextView(tr, str, true);
else
((TextView) tr.getChildAt(field)).setText(str);
*/
// DECIMALFORMAT CODE
double douValue = Double.parseDouble(str);
DecimalFormat df = new DecimalFormat();
df.applyPattern("##,###,###.##");
df.setGroupingUsed(true);
str = df.format(douValue);
if (addRow)
create_addTextView(tr, str, true);
else
((TextView) tr.getChildAt(field)).setText(str);
}
I think your problem is that you store the numbers as Float. Float does not have very good precision - it actually has only 23 binary digits of precision as seen here. This means that you can not store accurately in float 7 digits before the decimal point or even worse - 7 digits before the point and a couple after. This means that you have incorrectly chosen the type of the balance variable - you can not store in Float 8+2. I would recommend you to change the type to Double, which has significantly larger range of precision.
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);
}