How to set Text Number Format? - java

i was made this method to show value of int into text view
texton= (TextView)findViewById(R.id.textcolumn);
texton.setText(String.valueOf(score));
so it will show like this
but i want to make the number text format like this, it is possible?

You can use DecimalFormat .
public class DecimalFormat extends NumberFormat
DecimalFormat is a concrete subclass of NumberFormat that formats
decimal numbers. It has a variety of features designed to make it
possible to parse and format numbers in any locale, including support
for Western, Arabic, and Indic digits. It also supports different
kinds of numbers, including integers (123), fixed-point numbers
(123.4), scientific notation (1.23E4), percentages (12%), and currency
amounts ($123). All of these can be localized.
Please have a look here
NumberFormat
How can I format a String number to have commas and round?
So Try this way ,
DecimalFormat formatter = new DecimalFormat("#,###.000");
String get_value = formatter.format(score);
texton= (TextView)findViewById(R.id.textcolumn);
texton.setText(get_value);
Logic Courtesy

You can use DecimalFormat before setting the value in textView
texton.setText(setDotsDigit(score));
public static String setDotsDigit(double value)
{
return new DecimalFormat("###.###.###").format(value);
}

You should use DecimalFormat to format your score value first.
DecimalFormat formatter = new DecimalFormat("#,###.00")`;
String s = formatter.format(score);
texton = (TextView)findViewById(R.id.textcolumn);
texton.setText(s);
Hope it will help you.

Related

How to use add dot in Java's DecimalFormat to currency?

I'm trying to find a way to display currency with a dot so for instance it should be
1.234,56 kr.
At the moment I'm using
pattern = "#,##0.00 ¤";
new DecimalFormat(pattern);
This doesn't work as the Danish krone is for some reason defined there as kr instead of officially recognized kr.
I've looked for a way to escape these characters using Unicode value that I would add to pattern but that doesn't work. In the official documentation here I don't see a way to do it either.
TLDR: I want to add full stop after currency symbol. So at the moment I have it like this kr , what I want to get is kr. .
The output of currency values depends on the respective country setting. If you want to explicitly have a decimal point as in your case, you have to set a corresponding locale for the Numberformat. E.g. English for a point.
For Example:
public String FormatWithPoint(double yourValue){
NumberFormat nf = NumberFormat.getNumberInstance(Locale.ENGLISH);
nf.setGroupingUsed(false);
return nf.format(yourValue);
}
Edit: If you need more control, you can also do the following:
public String FormatCurreny(double yourValue){
NumberFormat nf = NumberFormat.getCurrencyInstance();
nf.setGroupingUsed(false);
DecimalFormatSymbols dfs = new DecimalFormatSymbols();
dfs.setCurrencySymbol("kr.");
dfs.setMonetaryDecimalSeparator('.');
((DecimalFormat) nf).setDecimalFormatSymbols(dfs);
return nf.format(yourValue);
}
If you just want the dot after the currency symbol you can set a custom currency symbol. Here I did it using euros (note that instead of "€." you can put my_symbol.getCurrencySymbol()+"." if you want it for all currency and not just one):
DecimalFormatSymbols my_symbol = new DecimalFormatSymbols();
my_symbol.setCurrencySymbol("€.");
String pattern = "###,###.###¤";
DecimalFormat decimalFormat1 = new DecimalFormat(pattern, my_symbol);
String format = decimalFormat1.format(987654321.321);
System.out.println(format);
This gives
987.654.321,321€.

The NumberFormatter function I made for JFormattedTextField, doesn't allow typing decimal numbers

In order to limit user's input to a specific numeric range I created this function:
public static final Locale GR=new Locale("el", "GR");
public static NumberFormatter getMyNumberFormatter(){
NumberFormatter formatter = new NumberFormatter(NumberFormat.getInstance(GR));
formatter.setValueClass(Double.class);
formatter.setAllowsInvalid(false);
formatter.setCommitsOnValidEdit(true);
formatter.setMinimum(0.0);
formatter.setMaximum(10000000.0);
DecimalFormat df = (DecimalFormat)DecimalFormat.getInstance(GR);
df.setGroupingUsed(true);
formatter.setFormat(df);
return formatter;
}
I applied this formatter to a JFormatedTextfield but it worked only on integer values. I want user to be able to type float numeric values from 0.0 to 10000000.0 but the current formatter allows only integers. Automatic grouping works perfect. Any suggestions?
As I remember JFormattedTextField is a pain to use.
I assume that the DecimalFormat is not allowing numbers with just a decimal point, based on the following section of the javadoc:
If you are going to allow the user to enter decimal values, you should either force the DecimalFormat to contain at least one decimal (#.0###), or allow the value to be invalid setAllowsInvalid(true). Otherwise users may not be able to input decimal values.
You can also try to add
df.setDecimalSeparatorAlwaysShown(true);
One note: it is a bit confusing that the JFTF is created using one NumberFormat and later a new one is set. More straightforward (not tested):
DecimalFormat df = (DecimalFormat)DecimalFormat.getInstance(GR);
df.setGroupingUsed(true);
df.setDecimalSeparatorAlwaysShown(true);
NumberFormatter formatter = new NumberFormatter(df);
...
or just
NumberFormatter formatter = new NumberFormatter();
...
formatter.setFormat(df);
Suggestion (better IMO than using a JFTF):
Extend a DocumentFilter and set it as filter of a new PlainDocument. Use a JTextField that uses that document.

How to make a string from a BegDecimal number which contained only the integral part

My question is about of toString() and toPlainString() methods of the BigDecimal dataTypewhich produces the output like
750.0000
150.0000
... etc
My question is how to specify the number of zeros followed after the dot? Is there a way to do it instead of String.replace(".0000", ".00") method?
Use DecimalFormat in combination with DecimalFormatSymbols:
DecimalFormatSymbols dfs = new DecimalFormatSymbols();
dfs.setDecimalSeparator('.');
DecimalFormat df = new DecimalFormat("##.##");
df.setDecimalFormatSymbols(dfs);
df.format(myNumber)
Without using DecimalFormatSymbols you would end up with a comma as a decimal seperator instead.
Please use the below code.
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(2);
String s = nf.format(1111.2222);
System.out.println(s);
Apart from decimal format you can also use setScale(2) like this
new BigDecimal("1.0000").setScale(2)
Also setScale allows you can specify the Rounding Mode
You could use setScale method and optinally you could choose rounding methodology of your own. Somethign like:
BigDecimal b = new BigDecimal("750.0000");
b.setScale(2);

How to format numbers as strings to be in the form "xxx.xxx.xxx,yy"in Java?

is there a class in Java that lets you format a number like "102203345.32" to this "102.203.345,32" and return a string type?
I would like to obtain a String where the thousands are separated by the '.' and the decimals are separated by a comma ','.
Could someone help me please? I found a class DecimalFormat and I tried to customize it:
public class CustomDecimalFormat {
static public String customFormat(String pattern, double value ) {
DecimalFormat myFormatter = new DecimalFormat(pattern);
String output = myFormatter.format(value);
return output;
}
}
but when I call the customFormat method like this: CustomDecimalFormat.customFormat("###.###,00") I get an exception...
What should I do?
Thanks!
Be sure to read and understand the Special Pattern Characters section of the Javadoc, especially this note:
The characters listed here are used in non-localized patterns. Localized patterns use the corresponding characters taken from this formatter's DecimalFormatSymbols object instead, and these characters lose their special status.
If you have done that, it should be clear to you that you must use the appropriate constructor and supply the appropriately configured separator/grouping chars, whereas in the pattern itself the dot and the comma have a special meaning.
All the complexity above is there for your convenience, actually: it allows you to customize the number format and have it localized.
Here's a code sample which worked for me:
final DecimalFormatSymbols syms = new DecimalFormatSymbols();
syms.setDecimalSeparator(',');
syms.setGroupingSeparator('.');
DecimalFormat myFormatter = new DecimalFormat("###,###.00", syms);
System.out.println(myFormatter.format(1234.12));
You can also use a variant where you apply the localized pattern, for more intuitive code:
final DecimalFormatSymbols syms = new DecimalFormatSymbols();
syms.setDecimalSeparator(',');
syms.setGroupingSeparator('.');
DecimalFormat myFormatter = new DecimalFormat("", syms);
myFormatter.applyLocalizedPattern("###.###,00");
System.out.println(myFormatter.format(1234.12));
First of all,
you misplaced the comma and decimal points. Your format should be : ###,###.00 instead of ###.###,00 ...
Also check with your Locale, it has an effect on the format. See the link below.
http://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html
You can try GERMAN number format
NumberFormat.getNumberInstance(Locale.GERMAN).format(102203345.32)

Currency formatting Issues

I am trying to convert an input string to euro/Bulgarian currency,I am having two scenario's.
First,
When input is 10,000 the Bulgarian format should be like 10 000 and euro format should be 10.000
Second,
if the input is 10.23 then both European and Bulgarian format should be 10,23.
I am trying to do using Big Decimal,Something like,
String s = "+000000055511.00";
BigDecimal b = new BigDecimal(s.replace(",", "."));
b.setScale(2, RoundingMode.HALF_UP);
System.out.println(b.toPlainString());
But I am not able to do it as an common utility which takes and converts into euro or bulgarian currency.Is there any utility for the same?Can somebody help me?
You may use java.text.NumberFormat.getCurrencyInstance(Locale) with appropriate locals. If there are no such locals which match your requirements then construct your own decimal formatter java.text.DecimalFormat with pattern ##' '##0.00 resp. ##,##0.00 plus appropriate currency sign. The formatter can be applied to BigDecimal:
String s = "+000000027511.00";
BigDecimal B = new BigDecimal(s);
// don't replace "." by ",": english number format expected here
b.setScale(2, RoundingMode.HALF_UP);
NumberFormat f = new DecimalFormat(...); //initialize as requested see docs
System.out.println(f.format(b));
Another question is why you don't want fraction digits if your number is 10,000? If this is really the case you must define two formatters more and must select them according to your creteria.
Hope this helps.

Categories

Resources