Example: If I have 7.2828, I just want to get the 2828 as an integer.
-
6I know this is a duplicate (I answered it at some point), but you realize 7.28 and 7.0028 will both end up with an answer of 28, correct? You'll have no idea what the original floating part was.Will Eddins– Will Eddins2009-08-18 16:00:08 +00:00Commented Aug 18, 2009 at 16:00
-
2can you clarify how you want these two numbers handled: 7.02828 and 7.000002828Allain Lalonde– Allain Lalonde2009-08-18 16:01:08 +00:00Commented Aug 18, 2009 at 16:01
-
How would you want the likes of 0.000000000125657542619998 dealt with?MartW– MartW2009-08-18 16:20:39 +00:00Commented Aug 18, 2009 at 16:20
Add a comment
|
4 Answers
If d is the original value, just do the following.
((int)(d * 10000)) % 10000
3 Comments
jmayor
is not specifically for this number. if you don't know the number of digits behing the dot. 10000 doesn't work.
Kirill V. Lyadvinsky
In C++ you should use static_cast to cast double to int. Final code should look like static_cast<int>(d*10000.0)%10000. C-cast is only for compatibility. Please, don't use it without reason.
avakar
JIa3ep, the question is tagged with c#. (Actually, for some reason I originally though the question was for Java :-) ).
I don't think you can. Most CPUs cannot represent 7.2828 as a double (IBM mainframes being the exception). The reason is that they represent doubles as a sum of powers of 2. The "7" part is easy: 1+2+4. The fracational bit is harder: 0.25+0.0.03125+0,0009765625..... - an infinite sequence. For practical reasons, this sequence is truncated. And the resulting double will be close to 7.2828. Perhaps 7.282800000000001245. This probably won't fit into an (32 bits) integer.