[英]How to get NSDecimalNumber from floatValue having same number of precision that the float value has?
I logged two NSDecimalNumber
我记录了两个NSDecimalNumber
NSLog(@"%@",[[NSDecimalNumber alloc] initWithFloat:2.675f]);
NSLog(@"%@",[[NSDecimalNumber alloc] initWithFloat:2.000f]);
I got the results in the console as 我在控制台中得到了结果
10:26 2013-05-16 10:23:20.807 SampleTest[1097:19d03] 2.674999952316284416
2013-05-16 10:23:22.484 SampleTest[1097:19d03] 2
My expected result is 2.0000
. 我的预期结果是2.0000
。 It is fine to have any number of zero's after decimal But should have atleast one zero after the decimal point. 小数点后可以有任意数量的零,但小数点后应至少有一个零。 It will be hard for me to change the NSDecimalNumber
datatype. 对我而言,更改NSDecimalNumber
数据类型将非常困难。
How can I acheive that. 我该如何做到这一点。 Can anyone help me out. 谁能帮我吗。 Thanks in advance. 提前致谢。
As decimal number is a represented in base-10 arithmetic. 以十进制表示的数字以10为基数。 An instance can represent any number that can be expressed as mantissa x 10^exponent where mantissa is a decimal integer 一个实例可以表示任何可以表示为尾数x 10 ^的数字,其中尾数是十进制整数
Therefore 0s after decimal gets truncated. 因此,十进制后的0s将被截断。 If you want explicitly then you need to use float
or double
. 如果您要明确表示,则需要使用float
或double
。
NSDecimalNumber *deciA=[NSDecimalNumber decimalNumberWithMantissa:2675 exponent:-3 isNegative:NO];
NSDecimalNumber *deciB=[NSDecimalNumber decimalNumberWithMantissa:2000 exponent:-3 isNegative:NO];
NSLog(@"deciA is %@",deciA);
NSLog(@"deciB is %@",deciB);
Output: 输出:
deciA is 2.675 分贝是2.675
desiB is 2 DesiB是2
You can do this way: 您可以这样做:
NSDecimalNumber *deciA=[[NSDecimalNumber alloc] initWithFloat:2.675f];
NSDecimalNumber *deciB=[[NSDecimalNumber alloc] initWithFloat:2.000f];
NSLog(@"deciA is %.3lf",[deciA doubleValue]);
NSLog(@"deciB is %.3lf",[deciB doubleValue]);
Output: 输出:
deciA is 2.675 分贝是2.675
desiB is 2.000 DesiB为2.000
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.