Retain formatting of a Double value - Java

前端 未结 3 1853
执念已碎
执念已碎 2021-01-23 04:37

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 bei

相关标签:
3条回答
  • 2021-01-23 04:53

    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 );  
    
    0 讨论(0)
  • 2021-01-23 04:53

    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.

    0 讨论(0)
  • 2021-01-23 05:10

    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

    0 讨论(0)
提交回复
热议问题