Printing the correct number of decimal points with cout

前端 未结 12 1493
孤独总比滥情好
孤独总比滥情好 2020-11-22 08:26

I have a list of float values and I want to print them with cout with 2 decimal places.

For example:

10.900  should be prin         


        
12条回答
  •  清酒与你
    2020-11-22 08:45

    with templates

    #include 
    
    // d = decimal places
    template 
    std::ostream& fixed(std::ostream& os){
        os.setf(std::ios_base::fixed, std::ios_base::floatfield); 
        os.precision(d); 
        return os; 
    }
    
    int main(){
        double d = 122.345;
        std::cout << fixed<2> << d;
    }
    

    similar for scientific as well, with a width option also (useful for columns)

    // d = decimal places
    template 
    std::ostream& f(std::ostream &os){
        os.setf(std::ios_base::fixed, std::ios_base::floatfield); 
        os.precision(d); 
        return os; 
    }
    
    // w = width, d = decimal places
    template 
    std::ostream& f(std::ostream &os){
        os.setf(std::ios_base::fixed, std::ios_base::floatfield); 
        os.precision(d); 
        os.width(w);
        return os; 
    }
    
    // d = decimal places
    template 
    std::ostream& e(std::ostream &os){
        os.setf(std::ios_base::scientific, std::ios_base::floatfield); 
        os.precision(d); 
        return os; 
    }
    
    // w = width, d = decimal places
    template 
    std::ostream& e(std::ostream &os){
        os.setf(std::ios_base::scientific, std::ios_base::floatfield); 
        os.precision(d); 
        os.width(w);
        return os; 
    }
    
    int main(){
        double d = 122.345;
        std::cout << f<10,2> << d << '\n'
            << e<10,2> << d << '\n';
    }
    

提交回复
热议问题