A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 李海鹏 中级黑马   /  2012-12-23 17:47  /  1864 人查看  /  5 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

/*double number = 12.2432123;
          BigDecimal big = new BigDecimal(number);
                  double results = big.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
                  System.out.println(results);*/


                /*DecimalFormat df = new DecimalFormat("##.00");  
        double x = 3.1415926;
        x = Double.parseDouble(df.format(x));
        System.out.print(x);*/


                /*double x = 3.1415926;
        x*=100;
        x = Math.round(x);
        x/=100;
        System.out.println(x);*/

这是一道简单的练习题适合初学者,三种方法。大家还有什么别的方法实现吗?

评分

参与人数 1技术分 +1 收起 理由
邵天强 + 1 神马都是浮云

查看全部评分

5 个回复

倒序浏览
public class test
{
        public static void main(String []args)
        {
                double x = 3.1415926;
                System.out.printf("%.2f",x);
        }       
}
回复 使用道具 举报
  1. public class test
  2. {
  3.         public static void main(String []args)
  4.         {
  5.                 double x = 3.1415926;
  6.                 int n=2;//小数点后两位
  7.                 int i,k;
  8.         for(i=0,k=1;i<n;i++) k*=10;
  9.         x=(double)((long)(x * k * 10 + 5)/10)/k;
  10.                 System.out.println(x);
  11.         }       
  12. }
复制代码

评分

参与人数 1技术分 +1 收起 理由
邵天强 + 1

查看全部评分

回复 使用道具 举报
许晓华 发表于 2012-12-23 19:45
public class test
{
        public static void main(String []args)

简洁方便,我喜欢!
回复 使用道具 举报
许晓华 发表于 2012-12-23 19:45
public class test
{
        public static void main(String []args)

这么简单呢
回复 使用道具 举报
public class Test {
        public static void main(String[] args) {
                double num = 1244.23344;
                String s = String.valueOf(num);
                int pos = s.lastIndexOf(".");
                String str = s.substring(pos+1, pos+3);
                System.out.println(str);
        }
}
在这里有用到的String类中的三个方法,
valueOf:返回int/long参数的字符串表示形式。
lastIndexOf:返回在此字符串中最右边出现的指定子字符串的索引。
substring: 返回一个新字符串,它是此字符串的一个子字符串。
具体说明可以查看Java doc,希望对你有帮助。
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马