Matching Excel's floating point in Java

后端 未结 6 1345
长发绾君心
长发绾君心 2020-12-11 02:06

I have an .xlsx spreadsheet with a single number in the top-left cell of sheet 1.

The Excel UI displays:

-130.98999999999

This is v

6条回答
  •  情话喂你
    2020-12-11 02:45

    You need to use BigDecimal for this (for not losing any precision).
    E.g. read the value as a String, then construct a BigDecimal from it.

    Here is an example where you don't lose any precision i.e. this
    is the way to obtain exactly the same number which the user sees in Excel.

    import java.math.BigDecimal;
    
    public class Test020 {
    
        public static void main(String[] args) {
            BigDecimal d1 = new BigDecimal("-130.98999999999069");
            System.out.println(d1.toString());
    
            BigDecimal d2 = new BigDecimal("10.0");
    
            System.out.println(d1.add(d2).toString());
            System.out.println(d1.multiply(d2).toString());
        }
    
    }
    

提交回复
热议问题