Advertisement

Truncating a float

Started by July 31, 2000 02:32 PM
5 comments, last by Rudan 24 years, 4 months ago
Here's an easy one (I think...) How do I truncate a float? and how do I do do the opposite(don't know what it's called), round a float up? thanks.... ****EDIT****** I'm so STUPID. forgot to tell you that i use C++ Edited by - Rudan on 7/31/00 2:36:58 PM
-----------------------------Reporter: Are they slow-moving, chief?Sheriff: Yeah, they're dead. They're all messed up.-Night of the living dead
#define floor(x) ( (int) (x) )

#define round(x) ( (int) ((x) + 0.5) )



_______________________________
"To understand the horse you'll find that you're going to be working on yourself. The horse will give you the answers and he will question you to see if you are sure or not."
- Ray Hunt, in Think Harmony With Horses
ALU - SHRDLU - WORDNET - CYC - SWALE - AM - CD - J.M. - K.S. | CAA - BCHA - AQHA - APHA - R.H. - T.D. | 395 - SPS - GORDIE - SCMA - R.M. - G.R. - V.C. - C.F.
Advertisement
If you want to round a negative float its a bit more complicated (i think)

=======================
Game project(s):
www.fiend.cjb.net
=======================Game project(s):www.fiend.cjb.net
try:

float f;
int x = (int) f;

You can lose the decimal point of a float by either assigning it straight to an int:

    myint = myfloat;[/source]in this case, the integer part will be retained and the decimal part is not copied - no rounding takes place.Or, you can cast to an int to save a variable such as[source]printf("%d\n", (int)myfloat);[/source]A contrived example I think you will agree.If you want to write some kind of rounding routine yourself - as there aren''t any specified by ANSI - the only two possibly related functions are ceil() and floor() - you will want to perform a subtraction of the integer part of the decimal, then test if it is greater/less than 0.5That''s probably not the quickest or most efficient way, but if your still wondering here''s a bit of code, uncondensed.[source]int roundnearest(float f){int i = f; // get decimal partf -= i;// if we are greater than half, return decimal part + 1if(f >= 0.5)return(i+1);// must not be, so just return ireturn(i);} // end roundnearest    


I didn''t test that, but it should work. Hope that was some help.

-Mezz
The standard C++ library includes the floor() and ceil() functions in math.h. They will round down and up respectively.


- Democritus

* Truth is universal *

- Democritus * Truth is universal *
Advertisement
Thanks for all the answers.

Anyone know wich alternetive is the fastest one?
-----------------------------Reporter: Are they slow-moving, chief?Sheriff: Yeah, they're dead. They're all messed up.-Night of the living dead

This topic is closed to new replies.

Advertisement