How to display BigDecimal value in a human readable format? - java

Suppose we have a BigDecimal variable setted up like this, and we can't change the way of it's creation:
BigDecimal num = new BigDecimal(6.0053);
So we'll see the following 'pretty' value after an output:
System.out.println(num); //0053000000000000824229573481716215610504150390625
The only way I've found to resolve this problem was using BigDecimal.valueOf():
System.out.println(BigDecimal.valueOf(num.doubleValue())); //6.0053
But is there a more simple solution?
Thanks in advance.

Use java.text.DecimalFormat to format the numbers.
NumberFormat format = new DecimalFormat("0.####");
System.out.println(format.format(num));
The format options can be found here

BigDecimal num = new BigDecimal(6.0053);
DecimalFormat df=new DecimalFormat("0.0000");
System.out.println(df.format(num));

You can use String.format with the "g" formatting type. It allows you to control how many digits you want, etc. See here for all formatting options.
BigDecimal num = new BigDecimal(6.0053);
String formated = String.format("%6.5g", num);
System.out.println(formated);
(Result : 6.0053)

System.out.println(new DecimalFormat("###,##0.00").format(myBigDecimalVariable));

Related

How to set specific format for E notation in Java

I need to convert some floats to format like this: 2,5000E-003, 2,8625E+000
I know i can do it like this:
String.format("%s,%sE%s", digitInt, digitAfterDot, digitDegree)
But I hope somebody knows more clever and natty solution
You can use:
String.format("%1.4e",12345.67890123)
The result of this is:
1,2346e+04
Here is some documentation
EDIT
If you need 3 digits in the exponent, you can use the DecimalFormat Formatter:
DecimalFormat format = new DecimalFormat("0.0000E000");
System.out.print(format.format(12345.67890123f));
Which outputs:
1,2346E004
Note that it does not come with a positive sign if the exponent is positive.
You can fix this with:
DecimalFormat format = new DecimalFormat("0.0000E000");
String result = format.format(12345.67890123f);
if (!result.contains("E-")) {
result = result.replace("E", "E+");
}

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.

Parse "45,978" to double value

I want to parse "45,978" to double which is read from a *.csv. Right now I am doing:
double P_current = Double.parseDouble(priceList.get(j));
However I am getting a number format exception for this string input:
java.lang.NumberFormatException: For input string: "45,978"
I know that I could change all the , in my csv file to a . which would probably work. However I do not want that, because I need the comma in this file. Is there any ways to parse this to double as-it-is?
I appreciate your answer!
If you don't want to replace anything, you can use Number and NumberFormat with Locale#GERMAN:
try {
NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
double number = nf.parse("45,978").doubleValue();
} catch(ParseException e) { }
If you want to be locale-independent, you can simply replace , with . to get the format that Double#parseDouble works with.
You should use the appropriate NumberFormat according to your locale :
NumberFormat format = NumberFormat.getInstance(Locale.GERMAN);
Number number = format.parse("45,978");
double d = number.doubleValue();
double parsed = Double.parseDouble(priceList.get(j).replace(',', '.'));
Or you could also use a DecimalFormat with the appropriate locale or symbols.
If your numbers are not from the English locale. Change the locale to a proper one:
NumberFormat format = NumberFormat.getInstance(Locale.FRENCH);
Number number = format.parse("45,978");
double d = number.doubleValue();
See more on NumberFormat here.

Parsing a String with an Exponent (Java)

I have a string similar to: 7.6E+7.
My question is simple: How do I turn this into its corresponding number: 76000000?
I have tried using substring to isolate the E+7 part, then parse the 7 part, then move the decimal places over 7. Is there an easier way to do this?
Thank you!
long n = Double.valueOf("7.6E+7").longValue();
System.out.println(d);
// prints 76000000 to the output.
I suggest using Double.parseDouble():
double val = Double.parseDouble(str);
where str is the input string.
You can use Double.parseDouble() to get it as a number.
String e = "7.6E+7";
System.out.println(Double.parseDouble(e));
Giving the output 7.6E7. If you do not want the E in the output you can use
NumberFormat f = NumberFormat.getInstance();
f.setGroupingUsed(false);
System.out.println(f.format(Double.parseDouble(e)));
Which will give you the output 76000000 without casting to a whole number. Eg adding 0.1 to the number will give the output 76000000.1
If you are sure the number can ultimately be cast into an integer without losing precision than alternatively you could do:
int d = (int) Double.parseDouble("7.6E+7");
System.out.println(d);
Which prints 76000000 to the output.

Categories

Resources