iPhone / Obj C:为什么转换浮点数为int:(int)float * 100不起作用? [英] iPhone/Obj C: Why does convert float to int: (int) float * 100 does not work?
问题描述
在我的代码中,我使用float来进行货币计算,但舍入已经产生了不希望的结果,所以我试图将其全部转换为int。在我的init函数中,尽可能少地改变了基础结构,我做了这个:
pre code $ - (id)initWithPrice :(浮)p;
{
[self setPrice:(int)(p * 100)];
我在主要部分乘以100 b / c,给出的值如.xx至2位小数。我不正常地注意到,对于浮点数1.18,int整数为117.有没有人知道它是这样做的?浮动离开它为1.18。我希望它是118美元的int equiv以美分。
谢谢。
浮点总是有点不准确。使用IEEE浮点编码,可以精确地表示两个幂(例如4,2,1,0.5,0.25,0.125,0.0625,...),但是像0.1这样的数字总是一个近似值(只要把它表示为一个和(int)强制转换会截断任何进来的数据,所以如果p * 100由于这个不精确性而解析为117.9999995,那么将会变成1.17而不是1.18。
更好的解决方法是在p * 100上使用类似roundf的东西。更好的办法是,如果你可以上游,并在整个程序中使用整数完全转换为定点数学。
In my code, I am using float to do currency calculation but the rounding has yielded undesired results so I am trying to convert it all to int. With as little change to the infrastructure as possible, in my init functions, I did this:
-(id)initWithPrice:(float)p;
{
[self setPrice:(int)(p*100)];
}
I multiply by 100 b/c in the main section, the values are given as .xx to 2 decimals. I abnormally I notice is that for float 1.18, the int rounds it to 117. Does anyone know it does that? The float leaves it as 1.18. I expect it to be 118 for the int equiv in cents.
Thanks.
Floating point is always a little imprecise. With IEEE floating point encoding, powers of two can be represented exactly (like 4,2,1,0.5,0.25,0.125,0.0625,...) , but numbers like 0.1 are always an approximation (just try representing it as a sum of powers of 2).
Your (int) cast will truncate whatever comes in, so if p*100 is resolving to 117.9999995 due to this imprecision , that will become 1.17 instead of 1.18.
Better solution is to use something like roundf on p*100. Even better would be if you can go upstream and fully convert to fixed-point math using integers in the entire program.
这篇关于iPhone / Obj C:为什么转换浮点数为int:(int)float * 100不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!