Retain precision with double in Java

前端 未结 22 3077
情歌与酒
情歌与酒 2020-11-21 05:15
public class doublePrecision {
    public static void main(String[] args) {

        double total = 0;
        total += 5.6;
        total += 5.8;
        System.out         


        
22条回答
  •  执念已碎
    2020-11-21 05:54

    You may want to look into using java's java.math.BigDecimal class if you really need precision math. Here is a good article from Oracle/Sun on the case for BigDecimal. While you can never represent 1/3 as someone mentioned, you can have the power to decide exactly how precise you want the result to be. setScale() is your friend.. :)

    Ok, because I have way too much time on my hands at the moment here is a code example that relates to your question:

    import java.math.BigDecimal;
    /**
     * Created by a wonderful programmer known as:
     * Vincent Stoessel
     * xaymaca@gmail.com
     * on Mar 17, 2010 at  11:05:16 PM
     */
    public class BigUp {
    
        public static void main(String[] args) {
            BigDecimal first, second, result ;
            first = new BigDecimal("33.33333333333333")  ;
            second = new BigDecimal("100") ;
            result = first.divide(second);
            System.out.println("result is " + result);
           //will print : result is 0.3333333333333333
    
    
        }
    }
    

    and to plug my new favorite language, Groovy, here is a neater example of the same thing:

    import java.math.BigDecimal
    
    def  first =   new BigDecimal("33.33333333333333")
    def second = new BigDecimal("100")
    
    
    println "result is " + first/second   // will print: result is 0.33333333333333
    

提交回复
热议问题