Archived

This topic is now archived and is closed to further replies.

How to make 0.4217 to become 0.42?

This topic is 5176 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

I sucked when comes to floatin'' point numbers. So an integer 0x1234 I can simply use mask 0xFF00 and make it 0x1200, but for a floatin'' point number I have no idea how this can be done. I need to remove the less significant digits at the back, and leave only two digits in front. Is there any similar maskin'' way? Gosh maybe my brain isn''t functionin'' well for now, I hope y''all can help me out with this one. Thanks in advanced!

Share on other sites
Maybe there ist an shorter/faster way but this should work:

float a = 0.4217
float result = float(int(a * 100.0f + 0.5f)) / 100.0f;

so 0.4217 -> 0.42 and 0.4250 -> 0.43

and without that "+ 0.5f" it just cuts off after the first two digits.

[edited by - Oesi on October 11, 2003 3:07:43 AM]

Share on other sites
void TruncateToNPlaces(float &n, int p){     float r(10.0f);     int i(0),t(p-1);     for(;i<t;++i)          r *= 10.0f;     t=n*r;     n=t/r;}

Where n is the number and p is the number of places to truncate to.

Later,
ZE.

p.s. it's brute force and not in the slightest bit efficient. I'm sure someone much smarter than me will (or already has) come up with a better solution, but at least this will give you an idea of the algorithm.

//email me.//zealouselixir software.//msdn.//n00biez.//

[edited by - zealouselixir on October 11, 2003 3:08:12 AM]

[edited by - zealouselixir on October 11, 2003 3:08:32 AM]

Share on other sites
Thanks guys! Both are actually the same way, one being straight
forward and another being generic. Originally I thought there
would be a way of maskin'' off the bits at the back if I
understand how floatin'' points are stored in memory. Kinda like
castin'' a FLOAT to DWORD and mask out those bits. But these two
methods work for me!

• Forum Statistics

• Total Topics
628647
• Total Posts
2984035

• 10
• 9
• 9
• 10
• 21