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.
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 have tried
System.out.println(myLorry.toString(registration, myCar.calcCharge()));
which outputs
Registration: TA17 NDD Charge: 7.0
I want my program to output
Registration: TA17 NDD Charge: £7.00
How can I format this correctly?
EDIT:
Why doesn't formatting work correctly? It says it's expecting two parameters but can only find one. I need to call objects using the toString method.
System.out.printf("%s £%.2f" ,myCar.toString(registration, myCar.calcCharge()));
like #davidxxx suggest in comment you can use
DecimalFormat d = new DecimalFormat("'£'0.00");
System.out.println(d.format(7.0));
Output
£7,00
If you have a problem with dot(.) and comma(,) then you can use DecimalFormatSymbols :
DecimalFormat d = new DecimalFormat("'£'0.00");
DecimalFormatSymbols sym = DecimalFormatSymbols.getInstance();
sym.setDecimalSeparator('.');
d.setDecimalFormatSymbols(sym);
one solution is to use the printf.
e.g.
double value = 7.0;
System.out.printf("%s%.2f","£", value);
output:
£7.00
In fact you should consider two things :
formatting the number value with the fixed number of digits for the floating part.
setting the decimal separator character.
The second point may matter as according to the locale set by the JVM, you could get a distinct result : £7.00 or £7,00
So, you could specify the "£0.00" pattern in DecimalFormat and create the DecimalFormat instance with a specific DecimalFormatSymbols that ensures that you will use as decimal symbol the . character.
You could do it for example :
float f = 7;
DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols();
otherSymbols.setDecimalSeparator('.');
NumberFormat formatter = new DecimalFormat("£0.00", otherSymbols);
String valueFormated = formatter.format(f);
But in fact a more simple way would be to use the String.format() method by specifying both the expected pattern (two digits for the floating part) and a Locale that uses the . as decimal separator :
float f = 7;
String valueFormated = String.format(Locale.US, "£%.2f", f);
Solved it! I was looking in completely the wrong part of my program, here is my solution:
String toString(String rn, double calcCharge)
{
DecimalFormat d = new DecimalFormat("£0.00");
return "Registration: " + rn + " Charge: " + d.format(calcCharge());
}
I had to modify a class that my subclasses inherited from.
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 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 ) );
DecimalFormat df2 = new DecimalFormat("#.##");
double zipf = 0.23951367781155017;
String zipt = df2.format(zipf);
System.out.println(zipt);
And I get "0,24"
The problem with this is then I want to use it as a double. But the Double.valueOf(); method fails due to the comma being there in the string output. Any way to solve this?
For decimal dot, you should create an instance with english locale like this:
NumberFormat nf = NumberFormat.getNumberInstance(Locale.ENGLISH);
nf.setMinimumFractionDigits(2);
nf.setMaximumFractionDigits(2);
String zipt = nf.format(zipf);
System.out.println(zipt);
I also suggest setting rounding to HALF_UP, because default rounding is not what most of us would expect: http://docs.oracle.com/javase/1.5.0/docs/api/java/math/BigDecimal.html#ROUND_HALF_EVEN
nf.setRoundingMode(RoundingMode.HALF_UP);
Use different locale.German has dot
NumberFormat nf = NumberFormat.getNumberInstance(Locale.GERMAN);
DecimalFormat df = (DecimalFormat)nf;
Alternative woud be to use string and then modify string to your needs.After that just parse to double.All done :)
Your problems is the local that your JVM is using , try to change at your current local.
Use DecimalFormat constructor that allows you to specify locale
new DecimalFormat("#.##", new DecimalFormatSymbols(new Locale("en")));
you could "format" your double manually but cutting of the decimal places like this:
DecimalFormat df2 = new DecimalFormat("#.##");
double zipf = 0.23951367781155017;
String zipt = df2.format(zipf);
System.out.println(zipt);
long zipfLong = Math.round(zipf*100);
double zipfDouble = zipfLong/100.0;
System.out.println(zipfDouble);
with Math.round you make sure the that 0.239.. becomes 0.24. zipf*100 will "cut" off the additional decimal places and zipfLong/100.0 will add the decimal places again. Sorry, bad explanation but here is the output:
0,24
0.24
And you can reuse the new zipfDouble as a double value without casting or taking care of locale settings.