开发者

Get the decimal point

How to get decimal point of a number? For example:开发者_如何学Go

If I have 1.5 how to get the 5 number?


int result = static_cast<int>(fmod(number, 1)*10);

EDIT: or simpler and probably faster:

int result = static_cast<int>(number*10)%10;

EDIT: to make it work also for negative numbers you may do:

int result = abs(static_cast<int>(number*10))%10;


Say you have x=234.537

floor(x*10) gives you 2345

you then just need to get the remainder of a division by 10

So:

int firstDecimal = floor(x*10)%10


Here:

(int) (n*10) % 10


There is a nice simple way to do it.

int GetFirstDecimalPlace( float f )
{
    const float dp = f - floorf( f ); // This simply gives all the values after the 
                                      // decimal point.
    return static_cast< int >( dp * 10.0f ); // This move the value after the decimal 
                                             // point to before it and then casts to an
                                             // int losing all other decimal places.
}


A way to work with negative numbers using no macro/function calls:

n < 0 ? (int) (-n * 10) % 10 : (int) (n * 10) % 10
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜