double displaying very long number

后端 未结 4 629
我寻月下人不归
我寻月下人不归 2021-01-15 00:14

I have a simple calculation that uses doubles but I\'m getting an unexpected result and I can\'t understand why?

import java.util.Scanner;
public class Versa         


        
4条回答
  •  盖世英雄少女心
    2021-01-15 01:07

    You cannot represent decimal values precisely whilst operating on doubles (or floats). Use BigDecimal instead.

    Edit (2)

    Example here:

    BigDecimal amount = new BigDecimal("2.99");
    amount = amount.add(new BigDecimal("25.00"));
    System.out.println(amount.toString());
    

    Ouput:

    27.99
    

提交回复
热议问题