float price;
int quantity;
double s = price*quantity;
两个变量相乘后有7位小数  怎么用DecimalFormat类来控制结果到2位小数  如果输入整数如:500也要能转成500.00

解决方案 »

  1.   

    DecimalFormat df=new DecimalFormat();
    df.applyPattern("#0.00");float price=123123.23423432; 
    int quantity=3; 
    double s = price*quantity; 
    String sh=df.format(s);
    System.out.println(sh);
      

  2.   

    给你段代码参考吧:
    /**
     * 保留小数点后2位
     * 
     * @param value
     * @return
     */
    public static String number2String(Number value) {
    value = value == null ? 0 : value;
    DecimalFormat a = new DecimalFormat("#.##");
    a.applyPattern("0.00");
    return a.format(value);
    }
      

  3.   

    DecimalFormat df=new DecimalFormat(); 
    df.applyPattern("#0.00");  float price=123123.23423432F;  
    int quantity=3;  
    double s = price*quantity;  
    String sh=df.format(s); 
    System.out.println(sh);
    我忘了加个F了float price=123123.23423432F;
      

  4.   


    public class DemoClass {
    public static void main(String[] args) { 
    NumberFormat nf=new DecimalFormat("#0.00"); 
    int quantity=3;  
    int s = 300*quantity;  
    System.out.println(nf.format(s));

    }
      

  5.   

    嗯,如果用的是 JDK 5 或以上版本的话,还可以采用 C 风格的格式化:String str = String.format("%.2f", s);