如何把java得出的数值,保留小数点2位四舍五入

来源:百度知道 编辑:UC知道 时间:2024/05/09 12:14:00
刚开始学习网页设计,大家帮助看看

做了一个小程序,比较简单,
我想把得出的最后数值,自动保留小数点后2位,并且四舍五入,

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>油费计算</title>
</head>
<script type="text/javascript">
function account()
{
var a=document.all.a.value;
var b=document.all.b.value;
var c=a/b*100;
document.all.c.value=c;

}
getValue();
</script>
<body>
<form name="form1">
加油数:<input id="a" type="text" >
历程数:<input id="b" type="text" onkeyup="account()">
总和 <input name="" type="text" id="c" maxlength="4">
<input type="button" onclick="account()" value="计算">
</form> <

// 方式一:
double f = 3.1516;
BigDecimal b = new BigDecimal(f);
double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

// 方式二:
new java.text.DecimalFormat("#.00").format(3.1415926);
// #.00 表示两位小数 #.0000四位小数 以此类推…

// 方式三:
double d = 3.1415926;
String result = String.format("%.2f", d);
// %.2f %. 表示 小数点前任意位数 2 表示两位小数 格式后的结果为f 表示浮点型。

//方法四:
Math.round(5.2644555 * 100) * 0.01d;
//String.format("%0" + 15 + "d", 23) 23不足15为就在前面补0

我写的C语言的算法,应该你可以转换下吧?呵呵!
就是通过整形数据的特点了;

例如该变量为float x;浮点型数据

四舍五入的算法为:
{int i=0; 整型数据;
i=(2*x*100+1)/2;
x=(float)i/100;
}
当保留小数点后两位是用100;3为是1000,1位是当然是10了;

明白?

唉!没学过,看着有点困难。

c = Math.round(c*100)/100