Converting a BigDecimal Number to the format of ###.# - java

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.

Related

Java - Format a String to show a pound sign and a decimal with two leading zeroes using objects and the toString method?

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.

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);

Java DecimalFormat

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.

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.

Formatting in java

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).

Categories

Resources