Author | Message | Time |
---|---|---|
sixb0nes | Hello. I've come across a rather interesting problem involving float to int conversions. If I have a float, say, 98.85, and I assign an int to this float times 100... [code] float myfloat = 98.85; int myint = myfloat * 100; [/code] myint becomes 9884, which is not what I want. Is there anyway to do this float->int conversion without losing precision and without making myint a float? I've figured a rather hack-like workaround by simply adding one to myint, but I would much rather a solution which did not involve this step. Thanks. | April 13, 2006, 11:45 PM |
rabbit | Floats are weird in C++. Your '98.85' is actually '98.849999...' Adding 0.01 and then multiplying should work. | April 13, 2006, 11:57 PM |
Maddox | [quote author=sixb0nes link=topic=14770.msg150578#msg150578 date=1144971913] Hello. I've come across a rather interesting problem involving float to int conversions. If I have a float, say, 98.85, and I assign an int to this float times 100... [code] float myfloat = 98.85; int myint = myfloat * 100; [/code] myint becomes 9884, which is not what I want. Is there anyway to do this float->int conversion without losing precision and without making myint a float? I've figured a rather hack-like workaround by simply adding one to myint, but I would much rather a solution which did not involve this step. Thanks. [/quote] Try this... [code] float myfloat = 98.85f; int myint = (int)myfloat * 100; [/code] | April 15, 2006, 10:43 PM |
Myndfyr | [quote author=Maddox link=topic=14770.msg150640#msg150640 date=1145140980] [quote author=sixb0nes link=topic=14770.msg150578#msg150578 date=1144971913] Hello. I've come across a rather interesting problem involving float to int conversions. If I have a float, say, 98.85, and I assign an int to this float times 100... [code] float myfloat = 98.85; int myint = myfloat * 100; [/code] myint becomes 9884, which is not what I want. Is there anyway to do this float->int conversion without losing precision and without making myint a float? I've figured a rather hack-like workaround by simply adding one to myint, but I would much rather a solution which did not involve this step. Thanks. [/quote] Try this... [code] float myfloat = 98.85f; int myint = (int)myfloat * 100; [/code] [/quote] That would result in myint == 9800. | April 15, 2006, 11:26 PM |
JoeTheOdd | I think he may have meant [tt]int myint = (int)(myfloat * 100);[/tt] so that the multiplication would process before the casting. | April 16, 2006, 3:07 AM |
rabbit | It would automatically be cast to int because he is multiplying by an int and storing as an int. A typecast is not needed. | April 16, 2006, 3:07 PM |