double a = 1.3333335555; JAVA里用什么方法取小数点后两位?? 求助中。。 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 1 浮点数永远是不准确的2 所谓取2位,只有在显示的时候才有效System.out.println(String.format("%.2f",1.333333555)); double a = 1.3333335555; BigDecimal bd = new BigDecimal(a); System.out.println(bd.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()); 额,可以用Math.round或者floor等其他取整方法,先放大100倍,然后缩回来 public static void main(String[] args) { double a = 1.3333335555; String str = String.valueOf(a); int index = str.indexOf('.') + 1; str = str.substring(index, index + 2); System.out.println(str); } 这么做只是输出控制了 没返回一个double值吧 我的意思大家没有明白吧。用Math.round(1.333333555*100)/100确实可以得到 1.33这个数字,不过如果你要继续使用浮点数类型的的话,依然是不准确的! System.out.printf("%.2f", 1.3333335555); http://blog.csdn.net/silentbalanceyh/archive/2009/09/28/4608360.aspx最开始的第一个小节我写了如何处理浮点数据的,可以参考一下 用double表示的浮点数本来就不是精确的 转换成string类型再取最后两位 System.out.println((int)(a*100)/100.0);我试了,可以的!! 用Process对象执行一命令,如果获得其输出啊? 一个小问题,this和 类名.this有什么不同 小問題問一下 问个比较烂的问题:applet界面,调用access数据库报错一大堆 JLabel上如何放置按钮 跪求!大哥大姐行行好! 用jxl操作excel文件,我想读取日期单元格为yyyy-mm-dd格式,请问怎样设置? 数据库连接池是不是只能生活在容器中? 作用域修饰符? 请问一个菜鸟问题 如何重写for循环?高手何不进来看看? 寻求正确的JAVA学习方法!
2 所谓取2位,只有在显示的时候才有效System.out.println(String.format("%.2f",1.333333555));
BigDecimal bd = new BigDecimal(a);
System.out.println(bd.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
double a = 1.3333335555;
String str = String.valueOf(a);
int index = str.indexOf('.') + 1;
str = str.substring(index, index + 2);
System.out.println(str);
}
用
Math.round(1.333333555*100)/100
确实可以得到 1.33这个数字,不过如果你要继续使用浮点数类型的的话,依然是不准确的!
System.out.printf("%.2f", 1.3333335555);
最开始的第一个小节我写了如何处理浮点数据的,可以参考一下