I have a question, I am doing an App that is a kind of bill however I don't know how to express in a textview for example:
1120 as $1.120 or something like this.
Thanks in advance
numberformat is your solution :
Test code :
int = 1236;
NumberFormat nf = NumberFormat.getInstance(Locale.US);
Log.i("test", nf.format(nb));
show output :
1,236
There are a number of solutions to format numbers in Android which of course depend on the nature of your app and your requirements.
Because you are using a money value in your example, I would look into Big Decimal at has numerous precision and rounding methods.
Here's a little example for you, note that it is not localised!
BigDecimal theAmount = new BigDecimal(int);
DecimalFormat decimalFormat = new DecimalFormat("$#,##0.00;-$#,##0.00");
// ^ This is set manually, you could use a localised format to have Android set the
// values based on locale like this: DecimalFormat.getInstance();
decimalFormat.setDecimalSeparatorAlwaysShown(true);
decimalFormat.setMinimumFractionDigits(3);
decimalFormat.setMaximumFractionDigits(3);
// ^ There are a lot of methods to check out here!
TextView yourTextView.setText(decimalFormat.format(theAmount.divide(new BigDecimal(1000))));
Good luck!
Related
Historically the Android phones sold in South Africa provided English.US and English.UK locale support, but recently English.ZA (South Africa) has made an appearance, on Android 9.0 Samsung Galaxy A10, for example.
This particular Locale is showing asymmetric treatment of number formats, using the Locale.DE (German/Dutch) convention when converting Floats and Doubles into character strings[*1], but raising Java.Lang.NumberFormatException when reading back the self-same generated strings. For instance:
// on output
Float fltNum = 1.23456F;
System.out.println(String.format(Locale.getDefault(),"%f",fltNum)); // prints '1,23456'
// on Input
String fltStr = "1,23456";
Float fltVal;
fltVal = Float(fltStr); // generates NumberFormatException
fltVal = Float.parseFloat(fltStr); // also generates NumberFormatException
// Giving the compiler Float hints fltStr = "1,23456F" does not help
// Only fltStr = '1.23456' converts into a Float.
The temptation would be to swap decimal separators on reads, but that is the task of Float.parseFloat(), a not of the programer, for doing so shall again break other Locale.DE-likes, such as Locale.ID (Indonesia) which my App supports.
My additional question directed more at Locale arbitrators is: Does English.ZA not imply English conformant as would say German.NA (Namibia) be German conformant? One would think the natural designation for this particular number conversion would be Dutch.ZA (colloquially 'Afrikaans'), for Dutch conformance, but Android designates it as English.ZA?
NB (*1) This Android English.ZA conforms only partially as it does not produce either the German point group separator or the local clerical (pen-and-paper) space character group separator.
Apologies for using 'Answer' to respond to diogenesgg's comment suggestion:
"Hi, please take a look at this answer stackoverflow.com/questions/5233012/…. TL/DR."
In it I found a few gems -
(1)
NumberFormat f = NumberFormat.getInstance(Locale.getDefault());
if (f instanceof DecimalFormat) {
((DecimalFormat) f).setDecimalSeparatorAlwaysShown(true);
}
But this is neutral and not value-specific so I added after the above,
(2) Given:
String axisValue("some-float-value-rendered as string");
NumberFormat nf = new DecimalFormat(axisValue);
Which I incorporate sequentially:
NumberFormat nf = new DecimalFormat(axisValue);
Number n;
if(nf instanceof DecimalFormat){
try{
n = nf.parse (axisValue);
axisComponent = (Double) n;
} catch (java.text.ParseException jtpe) {
jtpe.printStackTrace();
}
}
Notice the need to cast the Number n to Double.
This worked mostly under the problematic Locale English.ZA, until the value 0,00000 showed up.
For the string value "0,00000", NumberFormat decides Number n is a Long, and the system throws a (Long to Double) CastException.
I tried to trick NumberFormat in all ways I can to view 0 as a Float or Double to no avail, so 0 is a border problem that Number (NumberFormat.DecimalFormat) does not tolerate.
But this NumberFormat workaround does not resolve the assymmetry problem of Android 9 Locale.English(ZA).DecimalFormat emitting Locale.DE (comma decimal separator) but parsing only System.Primitives (decimal dot separator).
Incidentally, getting past the DecimalFormat problem exposed a myriad of other problems under this new-fangled English.ZA, of my App assuming system primitives working equally well with native resources. Well semantics so used require string comparison to work between primitive and native!
For example system file Primitive path names rendered in Native generating 'file not found', or even more problematic, using primitive string keys semantically only to being rendered meaningless on Native lookup.
I'm not sure which is the lesser evil, assymmetric locale English.ZA or my use of Primitives in semantics to thrust upon Natives. A futile exercise!
Right now I'm embarking on separating system primitives, including their semantic variants from ANY Native language resource strings ...
My lifetime of programming under system primitives needs an overall makeover.
Maybe I can keep an Assets repository for the primitives (resource or semantic) and have Natives look that up for system resources or for semantic Meaning.
I want to print a double No. in TextView like this format 10699657.6, currently this is like 1.06996576E7 . please can any one help me?
DecimalFormat dform = new DecimalFormat("0.###E0");
Similar question found here:
Convert scientific notation to decimal notation
There is DecimalFormat class, which does exactly what you want.
I am writing code in Adobe Flash Builder for an Android application. I have written my code to do some math and return the answer to a label field. I would like to know how do I return this answer to show only 1 spot after the decimal. Here is the code
lblAnswer.text = String(Number ((sldrABSL.value) + 46.7)/28.7);
If there are any suggestions please let me know.
If I understand this correctly, you have a string representing a number, which you want to be presented with only one decimal.
Fist of all, you'd have to convert the numeric value of the string to a double:
String stringOfNumber = "100.1233123";
Double number = Double.valueOf(stringOfNumber);
Secondly, you'd have to establish the format of which to represent the double (number of decimals):
DecimalFormat oneDigit = new DecimalFormat("#,##0.0");
Set the digit to a (i.e) TextView:
myTextView.setText("" + oneDigit.format(number));
I think this should work. Is this kind of what you were asking?
Edit: Not super certain as to how to set it to a textview, but in java, printing it to screen works like this:
System.out.println(oneDigit.format(number));
Edit2: Oh, and you'll need to this import:
import java.text.DecimalFormat;
Edit3:
TextView.setText("" + oneDigit.format(number));
works fine for me.
The decimal places uses the tofixed property. It must be added at the end of the specified number that needs to contain the decimal place.
'lblAnswer.text = String(Number ((sldrABSL.value) + 46.7)/28.7).toFixed(1);
The one specifies the number of decimal places that are used.
I'm trying to make a small Mathematical app in Android, but I am finding a little problem.
My problem is this, I would like my app to be able to correctly interpret the contents of the EditText, so that it is able to take as input not only numbers but also mathematical munctions xuch as sine cosine tangent logarithm etc.. I'm not an expert programmer, and I never found this type of problem before.
You could also try a java formel parser.
There are a bunch of them for java. For example: http://www.speqmath.com/tutorials/expression_parser_java/index.html
That could than look like this:
Parser prs = new Parser();
EditText et = (EditText)findViewById(R.id.edittext);
String expr = et.getText().toString();
String result = prs.parse(expr);
To install it you have to download:
http://www.speqmath.com/tutorials/expression_parser_java/html/files/expression_parser_java.zip
And then you have to copy the java files into your source folder in eclipse.
Did you do that this way?
If so could you post the exception.
You can try this:
EditText et = (EditText)additem.findViewById(R.id.edittext);
String item = et.getText().toString();
String splitter[] = item.split("\\d+");
if(splitter[0].equals("sin"))
// perform sine
//similarly for other functions
You need a parser.
You can either follow frugi's advice and use a java library, or you could implement your own.
A simple parser to implement and that is suitable for this problem is the Shunting Yard algorithm.
Pros with implementing your own parser:
Much more control over the grammar and expressions.
Good experience.
Fun.
Cons:
Takes more time to get ready (obviously) than a 3rd party library.
Could be buggy.
I would recommend writing your own!
My app is working on many devices without problems so far. But now I got my new Galaxy Tab with Android 3.2 where it crashes all the time. I found out that the problem was a float in an EditText.
I am using myEditText.setText(String.format("%.1f", fMyFloat)); to put the float in the EditText. But somehow the float on my 3.2 Galaxy Tab is generated with a comma instead of a point. When I read the EditText back the app crashes of course, telling me that this is no valid float because of the comma...
What is going wrong here?
Convert float to string..
From the documentation of String.format:
String.format(String format, Object... args)
Returns a localized formatted string, using the supplied format and arguments, using the user's default locale.
The quoted text above means that the output of String.format will match the default locale the user uses.
As an example a comma would be used as the decimal-point-delimiter if it's a user using Swedish locale, but a dot if it's using an American.
If you'd like to force what locale is going to be used, use the overload of String.format that accepts three parameters:
String.format (Locale locale, String format, Object... args)
Convert string to float..
Parsing an arbitrary string into a float using the default locale is quite easy, all you need to do is to use DecimalFormat.parse.
Then use .parse to get a Number and call floatValue on this returned object.
Your format call on your Galaxy Tab uses some default Locale which in turn uses , for floats. You could use String.format(Locale,String,...) version with specific locale to make things work.
Or you should've used same locale both for parsing and formatting the number. So you should probably go with NumberFormat to format and parse your floats.
String.format uses the locale you are in. You should do something like this if you want a dot:
NumberFormat formatter = NumberFormat.getInstance(Locale.US);
myEditText.setText(formatter.format(fMyFloat);
Have a look into NumberFormat for more formatting options
Use below code it's works for me:
NumberFormat nf = NumberFormat.getNumberInstance(Locale.US);
DecimalFormat df = (DecimalFormat)nf;
df.applyPattern(pattern);
String output = df.format(value);
System.out.println(pattern + " " + output + " " + loc.toString());
Summing up previous answers, an easy way to have the dot instead of the comma in all country, is this:
myEditText.setText(Locale.CANADA, String.format("%.1f", fMyFloat));
And you will have your String formatted with the dot