How would I make a java.text.NumberFormat instance that only allows positive integer numbers?
Actually, it would be nice if it only allowed from 1 and on.
Docs say that the formatting for postive/negative is divided by the ";" character, but putting nothing in the negative formatting or simply not using the ";" doesn't disables negative numbers.
These won't do it apparently:
NumberFormat nf = new DecimalFormat("#;");
// or
NumberFormat nf = new DecimalFormat("#");
// or
NumberFormat nf = new DecimalFormat("#;0");
Another approach would have been to create your own NumberFormat, that uses a DecimalFormat to convert from string to integer, and then apply any limits to that resulting integer.
Turns out jfxtras BigDecimalField (link to Javadocs) has a method for setting the minimum value allowed. This, combined with a NumberFormat that only allows for integer numbers, allows me to make a field that only accepts integers bigger or equal than 1.
bigDecimalFld.setFormat( new DecimalFormat( "#;" ) );
bigDecimalFld.setMinValue( new BigDecimal( 1 ) );
Related
I am trying to make a number in a BigDecimal variable match the format of ###.# where no matter what number is passed it will come out as ###.#
For example, if I was passed the number 1 in a BigDecimal variable the method would return 001.0
If I was passed 11.1 as a BigDecimal variable the method would return 011.1
I already have a bit of the code to make the decimal places match
BigDecimal x = new BigDecimal(1);
DecimalFormat df = new DecimalFormat("#.0");
String formatted = df.format(x);
So this would return 1.0 however I cannot figure out how to make the leading zeros appear before converting back to BigDecimal.
Can someone help me out or point me in the right direction?
Thanks everyone
Use a NumberFormat instance, with a Locale which uses the dot as decimal separator.
final BigDecimal x = new BigDecimal("11.1");
final NumberFormat nf = NumberFormat.getNumberInstance(Locale.ENGLISH);
nf.setMinimumFractionDigits(1);
nf.setMaximumFractionDigits(1);
nf.setMinimumIntegerDigits(3);
final String formatted = nf.format(x);
NumberFormat is basically a Factory, so for example in this case the underlying formatter returned by getNumberInstance is a DecimalFormat. I always prefer being abstracted off the real implementation.
You can also decide if you want to display the grouping comma or not.
nf.setGroupingUsed(true); // 123,456.0 - default value is true
nf.setGroupingUsed(false); // 123456.0
Use new DecimalFormat("000.0")
Examples
DecimalFormat df = new DecimalFormat("000.0", DecimalFormatSymbols.getInstance(Locale.US));
System.out.println(df.format(new BigDecimal("1"))); // prints: 001.0
System.out.println(df.format(new BigDecimal("11.1"))); // prints: 011.1
System.out.println(df.format(new BigDecimal("123.456"))); // prints: 123.5
System.out.println(df.format(new BigDecimal(".07"))); // prints: 000.1
System.out.println(df.format(new BigDecimal("123456"))); // prints: 123456.0
You can use the StringUtils of apache.
StringUtils.leftPad(number.toString(), 3, '0');
Where the first argument is the String to format, second argument is the number of to left places to validate, and the last argument is the char for complete.
Reggards.
I am not able to store value greater than "999" while using parseDouble function. This is my code:
NumberFormat formatter = NumberFormat.getNumberInstance();
formatter.setMinimumFractionDigits(2);
formatter.setMaximumFractionDigits(2);
double amount = Double.parseDouble(formatter.format(Double.parseDouble(balanceAmt.getText().toString())));
It is only storing value upto "999" not greater than that. It does not allow me to store value "1000" or greater.
Error message:
java.lang.NumberFormatException: For input string: "123,456.78"
The default method NumberFormat.format(String) automatically puts a comma separating thousands when setting it to formatted text. This comma can not be parsed into a double datatype because it only accepts '.' as the decimal split character and numbers around it.
This can be seen by this test:
double amount = Double.parseDouble(formatter.format(Double.parseDouble("1000")).replace(",", ""));
If the number requires a comma then use the .replace() method to replace it when parsing it to a double. Otherwise use a custom instantiation for your Number formatter such as:
NumberFormat formatter = new DecimalFormat("0000.00");
I am working under the assumption that balanceAmt.getText().toString() is returning 123,456.78 or similar.
NumberFormat formatter = NumberFormat.getNumberInstance();
formatter.setMinimumFractionDigits(2);
formatter.setMaximumFractionDigits(2);
double amount = Double.parseDouble(formatter.format(Double.parseDouble(balanceAmy.getText().toString().replace(",", ""))).replace(",", ""));
System.out.print(amount);
When you get the balance from balanceAmt, it has the comma, so you have to remove it. When if goes through the formatter, it re-adds the comma back, meaning you have to remove it again before the second parseDouble is done.
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 can I make Java use the ∞ symbol instead of the string "infinity" when printing/toString'ing floating-point values (float, double, Float, Double)?
You can't change the default toString method, which isn't for user display but for debug/logging.
But you may configure your own DecimalFormat :
DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.ENGLISH);
symbols.setInfinity("∞");
DecimalFormat decimalFormat = new DecimalFormat("#.#####", symbols);
You use it like this :
String str = decimalFormat.format(myDouble);
Note that the formater will automatically add a minus sign in case of negative infinity.
Good day.
I need to format a number in java.
So far I have this:
DecimalFormat df2 = new DecimalFormat( "#,###,###,##0.00" );
System.out.println(new Double(df2.format(balance)).doubleValue());
But it prints out this
110.0
121.0
133.1
146.41
161.05
But I need it to be with two digits in fraction part. How do I do it?
You don't have to get double value from formatted string.
Just use formatted string, which is returned from format() method of DecimalFormat.
So your code should be like the following:
DecimalFormat df2 = new DecimalFormat( "#,###,###,##0.00" );
...
System.out.println(df2.format(balance));
Your original code:
System.out.println(new Double(df2.format(balance)).doubleValue());
What you did in your code is: format the double value to string(which is formatted as you specified in the DecimalFormat instance). Then you convert the formatted string to Double instance and get double value from the object, which is double. And then printed it to console. So the formatted string is gone, and the double value is printed as normal.
"But I need it to be with two digits in fraction part. How do I do it?"
DecimalFormat df2 = new DecimalFormat( );
df2.setMinimumFractionDigits(2);
df2.setMaximumFractionDigits(2);
System.out.println(df2.format(balance));
You could also use the setMinimumFractionDigits method of DecimalFormat
df2.setMinimumFractionDigits(2);
your decimal format is right, but
what you are doing before you print this out is new Double(df2.format(balance)) which create new instant of double, which ignores your formatting.
so if you want to display or log your value df2.format(balance) this should be enough
ie:
System.out.println(df2.format(balance));
Try this pattern for formatting #,###,###,##.##-
DecimalFormat df2 = new DecimalFormat( "#,###,###,##.##" );
System.out.println(df2.format(balance));
This should be sufficient:
DecimalFormat df2 = new DecimalFormat("#,##0.00");
System.out.println(df2.format(balance));
The grouping for separator will follow "the interval between the last one and the end of the integer". So there is no benefit from over-specify. Example from the documentation of DecimalFormat:
The grouping separator is commonly used for thousands, but in some countries it separates ten-thousands. The grouping size is a constant number of digits between the grouping characters, such as 3 for 100,000,000 or 4 for 1,0000,0000. If you supply a pattern with multiple grouping characters, the interval between the last one and the end of the integer is the one that is used. So "#,##,###,####" == "######,####" == "##,####,####".
Another thing is that .format() method already output a String, so there is no point in converting it to double. It will cause Exception to be thrown when balance is more than 1000 (the point when separator comes into effect, and Double class cannot parse the String with separator).