Retain formatting of a Double value - Java

2019-02-25 18:59发布

问题:

I am using Poi to create Excel workbooks in Java. My raw data comes in as a string. I need to format the data to enter two decimal places into the cell where the number is being written. I use Double.parseDouble() to convert the string to numeric and then use DecimalFormat to format the numeric as a string. Another call to Double.parseDouble() to return the value to numeric (the cell where it is going is formatted numeric, so I can't use the string value) and I should be good. Problem is, that second call to Double.parseDouble() truncates any trailing zeroes off from the right of the decimal point. Anybody have an idea as to how I can coerce this value to read as, say, 1.50 rather than 1.5?

回答1:

I always want two decimals.

Solution: Always apply specific decimal format pattern.

Sample code snippet:

//java.text.DecimalFormat df = new java.text.DecimalFormat( "###0.00" );  
java.text.DecimalFormat df = new java.text.DecimalFormat();  
df.applyPattern( "###0.00" ); // always two decimals  

double dbl = 1.50d ;  

// prints: dbl =  1.5
System.out.println( "dbl = " + dbl );  

// prints: df.format( 1.5 ) = 1.50
System.out.println ( "df.format( " + dbl + " ) = " + df.format( dbl ) );

UPDATE:
OK, from your posting, I understand that you are trying to fill the numeric formatted cell only to print or show up with two decimal positions. You know by default all numeric fields are interpreted omitting trailing zeros. To achieve your requirement, you may require to use CellFormat and/or DataFormatter on your contextual Cell object, but when said Format, it is a String again.

I didn't try the following code but may help you.

DataFormatter dataFormatter = new DataFormatter();
dataFormatter.setDefaultNumberFormat( instanceOfDesiredDecimalFormat );  
// or  
// dataFormatter.setExcelStyleRoundingMode( instanceOfDesiredDecimalFormat );  

// apply this format on the cell you want
dataFormatter.formatCellValue( instanceOfNumericCellInContext );  


回答2:

You are actually doing nothing in most part of the code you described. You might as well just return Double.parseDouble(inputString). Doubles are stored in binary format and the leadin/trailing zeros make no sense. Perhaps the BigDecimal class is something for you.



回答3:

It appears we are at an impasse. As Mario pointed out, doubles are managed as binary and there is no way to format the binary as a double, except to convert it to a string with DecimalFormat, which is no longer a double. I explained this to my boss and he's ok with the solution of taking the raw double, so I'm closing this issue. Thanks to all for your help and support.

regards, Mike