黑马程序员技术交流社区
标题:
给定一个小数,保留该小数的后两位
[打印本页]
作者:
李海鹏
时间:
2012-12-23 17:47
标题:
给定一个小数,保留该小数的后两位
/*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);*/
这是一道简单的练习题适合初学者,三种方法。大家还有什么别的方法实现吗?
作者:
许晓华
时间:
2012-12-23 19:45
public class test
{
public static void main(String []args)
{
double x = 3.1415926;
System.out.printf("%.2f",x);
}
}
作者:
许晓华
时间:
2012-12-23 19:57
public class test
{
public static void main(String []args)
{
double x = 3.1415926;
int n=2;//小数点后两位
int i,k;
for(i=0,k=1;i<n;i++) k*=10;
x=(double)((long)(x * k * 10 + 5)/10)/k;
System.out.println(x);
}
}
复制代码
作者:
乔叶旭
时间:
2012-12-23 20:58
许晓华 发表于 2012-12-23 19:45
public class test
{
public static void main(String []args)
简洁方便,我喜欢!
作者:
李海鹏
时间:
2012-12-24 15:44
许晓华 发表于 2012-12-23 19:45
public class test
{
public static void main(String []args)
这么简单呢
作者:
罗利华
时间:
2012-12-29 18:24
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,希望对你有帮助。
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2