How to set Text Format? - java

A normal scoreboard text is like this
so i want to make te text format like this
this is the code
score = (TextView)findViewById(R.id.ct);
score.setText(String.valueOf(gamescore));
if (gamescore > highscore){
high.setText(String.valueOf(gamescore));
}
Anyone can explain? Thank's

You should use the String.format() method along with the formatter syntax. String.format() can be used to left-pad a string with zeroes, just like you want.
This code will give you the results that you want: high.setText(String.format("%06d", gamescore));
Let's look at what's going on in detail. We are using this syntax: %[flags][width]conversion
Always begin the format string syntax with a %.
Following % is 0, the zero-padding flag. This tells the formatter that the result will be zero-padded.
After the zero-padding flag is the width, or the minimum number of digits we want; in this case, 6.
Lastly, specify the conversion type. The desired result is formatted as a decimal integer, so we use d.
Here is an example:
int gamescore = 100;
String result = String.format("%06d", gamescore);
System.out.println(result);
Output: 000100

Related

What is the MessageFormat pattern to produce localized, full precision output for any double

Given the example code:
String format = "{0,number}"; // <- What do I put here?
double value = Math.PI * 1e-10;
System.out.println(value);
System.out.println(new MessageFormat(format, Locale.US).format(new Object[]{value}));
System.out.println(new MessageFormat(format, Locale.FRANCE).format(new Object[]{value}));
What do I use as the format string such that I get full precision output of any double value and that the output is localized? For example, the output of the current code is:
3.1415926535897934E-10
0
0
String.valueOf(double) correctly prints the full precision, but it isn't a message format and it is not localized. The message format decides the value is too small to bother with. For large numbers the results are even worse! MessageFormat prints 16 significant digits and then appends a bunch of zeros that do not accurately reflect the value stored in the double. E.g. with pi * 1e100 I get:
3.141592653589793E100
31,415,926,535,897,930,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000
31 415 926 535 897 930 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000
For your requirement and only for it, this is an easiest solution which fits to your code.
Using # symbol below, we show the digits only when they are not 0, otherwise they are being omit.
double value = Math.PI*1e-10;
String format = "{0,number,#.###############E0}"; // <- What do I put here?
System.out.println(value);
System.out.println(new MessageFormat(format, Locale.US).format(new Double[]{value}));
System.out.println(new MessageFormat(format, Locale.FRANCE).format(new Double[]{value}));
If you want to omit conversion of formatting numbers using scientific notifications, for example instead of 9.424777960769379E2( if in format #.###############E0) or 94.24777960769379E1 ( if in format ##.###############E0 ) to be 942.4777960769379, just use code below:
double value = Math.PI*1e-10;
String format = "{0,number,#.################}"; // <- What do I put here?
Take a look and if there is something you need additionally, feel free to ask!

Java format String with dynamic width and precision

How can we set dynamic width and precision while formatting string? I know the following code works good, but how can we do it in a formatter way?
int len = 3;
String s = "Andy";
System.out.printf("%1$" + len + "." + len + "s%n", s);
Output:
And
I have tried this one. It didn't throw an error, but prints different value than expected. (It looks so messy, but I've tried to pass the 'len' to width and precision. That's it. :) )
System.out.printf("%2$%1$d.%1$ds%n", len, s);
Output:
%1$d.3s
Is it doable? If so, how can we get same output as the former one?
Unfortunatly, the formatter used in String.format read the String from left to right, so it doesn't notice the new flag generated. This would have been possible if it will read from right to left but the problem would have been with the varags since you can pass to many parameters to the methods.
So the only way to format something like
String.format("|%ds", 5, "foo")
to output
| foo
Would be to format twice, this would not be the most effecient but the most readable (and that not even really true ......)
So my solution looks like this
String.format(String.format("|%%%ds", 5), "foo") //Here, I add a double %
the first formatter will return %5s that will be format again with the String.

Java output double numbers in exponential format

I have some double numbers that are outputted with this format:
Format.String("%1.4e",doubleNumber);
The result is 1.123456e+03. How can I set the number of cipher of exponent for getting this format:
1.123456e+003
I would have always 3 cipher after e symbol.
Thank you
UPDATE 1:
I have partially resolved:
DecimalFormat formatter = new DecimalFormat("0.000000E000");
System.out.println( formatter.format(doubleNumber) );
Now the number has always the format
1.123456e0xx
or
1.123456e-0xx
But it's not all resolved. I would have always printed the sign:
1.123456e+0xx or 1.123456e-0xx
How can I do?
http://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html
Thank you #TDG
private String formatter(double number){
DecimalFormat formatter = new DecimalFormat("0.000000E000");
String fnumber = formatter.format(number);
if (!fnumber.contains("E-")) { //don't blast a negative sign
fnumber = fnumber.replace("E", "E+");
}
return fnumber;
}
There's no built-in way to do that, you'd have to do it yourself.
Easiest would be to format like you did and then add the extra zeroes, if needed.
Also, it's String.format, not Format.String, and the "%1.4e" format you gave will result in 1.1235e+03, not 1.123456e+03.
There's nothing that I can see in the String or Formatter JavaDoc that allows you to do this directly. So I think you'll have to resort to some bit twiddling.
long exponentMask = 0x7ff0000000000000L; // per JavaDoc for Double
// the exponent is in bits 62-52, so I'm thinking a right-shift by 52
// bits would work. But I could be off by one.
int shiftExponentBy = 52;
long myDoubleAsLong = Double.doubleToLongBits(doubleNumber);
long rawExponent = myDoubleAsLong & exponentMask;
long shiftedExponent = rawExponent >> shiftExponentBy;
That gives you the exponent by itself. You should be able to extract the significand in a similar manner, then format each separately.
Update 1
It seems as though your Update 1 results in the same problem, just expressed differently. You need to format the exponent separately from the significand. DecimalFormat allows a positive pattern and a different negative pattern, but those are for positive and negative significands. You'd need a variant on those that allows for positive and negative exponents. I don't see any such thing. I'm standing by my original answer.

Parse double from JFormattedTextField

I've got a bug or something. I have a method that saves an article, like this:
class SaveArticleListener implements ActionListener {
//....
String s = textArticlePrice.getText().replace(',','.').replaceAll("\\s","");
double price = Double.parseDouble(s);
//....
}
Where textArticlePrice is a JFormattedTextField which configured like:
NumberFormat priceFormat = NumberFormat.getNumberInstance();
priceFormat.setMaximumFractionDigits(2);
priceFormat.setMinimumFractionDigits(2);
textArticlePrice = new JFormattedTextField(priceFormat);
textArticlePrice.setColumns(10);
And in the parseDouble method I'm getting every time:
java.lang.NumberFormatException: For input string: "123 456 789.00"
So replace works with a dot, but not with whitespace... Why?
You'd be better off using your NumberFormat to parse the String. Keep a reference to priceFormat, and then use
double price = priceFormat.parse(textArticlePrice.getText()).doubleValue();
The formatter that's being used to display the number is the same one then used to turn it back into a double so you know it's going to be parsing it in a compatible way.
Best of all is
double price = ((Number) textArticlePrice.getValue()).doubleValue();
which should work without any need for conversion if you've set your JFormattedTextField up properly. (The getValue() call returns an Object, so you need to cast it. It might return a Double or a Long, depending on what's in the text field, so the safe way to get a double out of it is to treat it as a Number, which is the supertype of both, and invoke its .doubleValue() method.)
Writing something that converts it into something that can be parsed by Double.parseDouble() is really not the right way to go because it's too fragile if the formatting of your text field changes later on.
Regarding your question" why doesn't it work with white spaces". White spaces are chars just like a,l,#,?,¡, but it only recognises ,12345, numbers together as a number, you cant make an int variable 'int number = 1 234; Its the same with parsing. Rather try,
s = s.replace(',','.');
s = s.replace(" ","");
Price = Double.parseDouble(s);
Assuming that '123 456 789.00' is one number.
please comment if this helped.
I did this now, it worked fine
String strNumber = "1 2 3 4 5 6.789";
double DblNumber = Double.parseDouble(strNumber);
System.out.Println(DblNumber);// this displays the number if your IDE has an output window

How can I format a String number to have commas and round?

What is the best way to format the following number that is given to me as a String?
String number = "1000500000.574" //assume my value will always be a String
I want this to be a String with the value: 1,000,500,000.57
How can I format it as such?
You might want to look at the DecimalFormat class; it supports different locales (eg: in some countries that would get formatted as 1.000.500.000,57 instead).
You also need to convert that string into a number, this can be done with:
double amount = Double.parseDouble(number);
Code sample:
String number = "1000500000.574";
double amount = Double.parseDouble(number);
DecimalFormat formatter = new DecimalFormat("#,###.00");
System.out.println(formatter.format(amount));
This can also be accomplished using String.format(), which may be easier and/or more flexible if you are formatting multiple numbers in one string.
String number = "1000500000.574";
Double numParsed = Double.parseDouble(number);
System.out.println(String.format("The input number is: %,.2f", numParsed));
// Or
String numString = String.format("%,.2f", numParsed);
For the format string "%,.2f" - "," means separate digit groups with commas, and ".2" means round to two places after the decimal.
For reference on other formatting options, see https://docs.oracle.com/javase/tutorial/java/data/numberformat.html
Given this is the number one Google result for format number commas java, here's an answer that works for people who are working with whole numbers and don't care about decimals.
String.format("%,d", 2000000)
outputs:
2,000,000
Once you've converted your String to a number, you can use
// format the number for the default locale
NumberFormat.getInstance().format(num)
or
// format the number for a particular locale
NumberFormat.getInstance(locale).format(num)
I've created my own formatting utility. Which is extremely fast at processing the formatting along with giving you many features :)
It supports:
Comma Formatting E.g. 1234567 becomes 1,234,567.
Prefixing with "Thousand(K),Million(M),Billion(B),Trillion(T)".
Precision of 0 through 15.
Precision re-sizing (Means if you want 6 digit precision, but only have 3 available digits it forces it to 3).
Prefix lowering (Means if the prefix you choose is too large it lowers it to a more suitable prefix).
The code can be found here. You call it like this:
public static void main(String[])
{
int settings = ValueFormat.COMMAS | ValueFormat.PRECISION(2) | ValueFormat.MILLIONS;
String formatted = ValueFormat.format(1234567, settings);
}
I should also point out this doesn't handle decimal support, but is very useful for integer values. The above example would show "1.23M" as the output. I could probably add decimal support maybe, but didn't see too much use for it since then I might as well merge this into a BigInteger type of class that handles compressed char[] arrays for math computations.
you can also use the below solution
public static String getRoundOffValue(double value){
DecimalFormat df = new DecimalFormat("##,##,##,##,##,##,##0.00");
return df.format(value);
}
public void convert(int s)
{
System.out.println(NumberFormat.getNumberInstance(Locale.US).format(s));
}
public static void main(String args[])
{
LocalEx n=new LocalEx();
n.convert(10000);
}
You can do the entire conversion in one line, using the following code:
String number = "1000500000.574";
String convertedString = new DecimalFormat("#,###.##").format(Double.parseDouble(number));
The last two # signs in the DecimalFormat constructor can also be 0s. Either way works.
Here is the simplest way to get there:
String number = "10987655.876";
double result = Double.parseDouble(number);
System.out.println(String.format("%,.2f",result));
output:
10,987,655.88
The first answer works very well, but for ZERO / 0 it will format as .00
Hence the format #,##0.00 is working well for me.
Always test different numbers such as 0 / 100 / 2334.30 and negative numbers before deploying to production system.
According to chartGPT
Using DecimalFormat:
DecimalFormat df = new DecimalFormat("#,###.00");
String formattedNumber = df.format(yourNumber);
Using NumberFormat:
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setGroupingUsed(true);
String formattedNumber = nf.format(yourNumber);
Using String.format():
String formattedNumber = String.format("%,.2f", yourNumber);
Note: In all the above examples, "yourNumber" is the double value that you want to format with a comma. The ".2f" in the format string indicates that the decimal places should be rounded to 2 decimal places. You can adjust this value as needed.

Categories