round public static long round(double a) Returns the closest long to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result, and casting the result to type long. In other words, the result is equal to the value of the expression: (long)Math.floor(a + 0.5d) Special cases:
double d = 5.6;
取证之后--> i = (int)(5.6+0.5);
如果你用数据库,可以定义decimal或money类型,
要不然自定义一个类,小数和整数部分分别存储
比方说我有一个数,我用两种方式都得到了,最后他们应该是一样的,但是由于在计算的过程中有四舍五入,所以导致后面两个结果就不一样了!
public static long round(double a)
Returns the closest long to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result, and casting the result to type long. In other words, the result is equal to the value of the expression: (long)Math.floor(a + 0.5d)
Special cases:
[code=Java]
double a=1.354;
a=Math.rint(a*100)/100;
code]
如
12.58 保存 1258 2
52.876 保存 52875 3
计算时,采用小数位数最大的作为基准,如上面的3
然后 小数位数比它小的,不断地乘10,如
int a = 1258;
for (int i=2; i<=3; i++) {a*=10;}
然后进行加减乘除相关处理,如
int b = 52876
double r = a + b;
如果是结果是直接保存的,可以保存 r 3
如果是要返回的,可以
for (int i=3; i>0; i--) {
double /= 10;
}
然后根据实际需要保留小数的位数进行四舍五入
class Money {
int intValue;
int pointPos;
public Money(double money) {
pointPos = String.valueOf(money).lastIndex(".");
intValue = (int)(money * Math.pow(10, pointPos));
}
}
String s = String.valueOf(money);
pointPos = s.length()-s.IndexOf(".");
decimal.Round() 是以四舍六入五成双!
结果 5.55
.ToString("N2") 是纯粹的四舍五入!
结果5.56楼主祝你好运。
* 四舍五入
*
* @param num
* 要四舍五入的数字
* @param roundBit
* 四舍五入位数 正数表示:小数点后位数;负数表示:小数前位数
* @return 四舍五入后的数字
*/
public static double round(double num, int roundBit) {
int piontBit = 1;
double numtmp = 0;
if (roundBit < 0) {
String tmpstr = "1";
roundBit = Math.abs(roundBit);
for (int i = 0; i < roundBit; i++) {
tmpstr += "0";
}
piontBit = Integer.parseInt(tmpstr);
roundBit = 0;
num = (double) (num / piontBit);
}
BigDecimal b = new BigDecimal(Double.toString(num));
BigDecimal one = new BigDecimal("1");
numtmp = b.divide(one, roundBit, BigDecimal.ROUND_HALF_UP)
.doubleValue();
return numtmp * piontBit; }
int Round( float f )
{
return _mm_cvt_ss2si( _mm_set_ss(f+f+0.5f) >> 1 );
}
int Floor( float f )
{
return _mm_cvt_ss2si( _mm_set_ss(f+f-0.5f) >> 1 );
}