直接上代码
NSString *showNum = [NSString stringWithFormat:@"%@",hitCountNumber];//直接显示字符串即可 方法源码复制
#pragma mark 精确计算
+ (nsdecimalnumber *)computationwithfirstnum:(nsstring *)firstnum//第一个计算参数 如:@"10000.0"
twonum:(nsstring *)twonum
type:(nsstring *)type// @"+",@"-",@"x",@"/"
scale:(int)scale//保留几位小数
{
//转化成nsdecimalnumber
nsdecimalnumber *g_firstnum = [nsdecimalnumber decimalnumberwithstring:firstnum];
nsdecimalnumber *g_twonum = [nsdecimalnumber decimalnumberwithstring:twonum];
//精度
/*
nsroundplain:四舍五入
nsrounddown:只舍不入
nsroundup:只入不舍
nsroundbankers: 在四舍五入的基础上加了一个判断:当最后一位为5的时候,只会舍入成偶数。比如:1.25不会返回1.3而是1.2,因为1.3不是偶数。
*/
nsdecimalnumberhandler *roundup = [nsdecimalnumberhandler
decimalnumberhandlerwithroundingmode:nsrounddown
scale:scale
raiseonexactness:no
raiseonoverflow:no
raiseonunderflow:no
raiseondividebyzero:yes];
nsdecimalnumber *computationnum;
if ([type isequaltostring:@"/"]) {//两个数相除
computationnum = [g_firstnum decimalnumberbydividingby:g_twonum withbehavior:roundup];
}
else if ([type isequaltostring:@"+"]){//两个数相+
computationnum = [g_firstnum decimalnumberbyadding:g_twonum withbehavior:roundup];
}
else if ([type isequaltostring:@"-"]){//两个数相-
computationnum = [g_firstnum decimalnumberbysubtracting:g_twonum withbehavior:roundup];
}
else if ([type isequaltostring:@"x"]){//两个数相x
computationnum = [g_firstnum decimalnumberbymultiplyingby:g_twonum withbehavior:roundup];
}
return computationnum;
}
网友评论