Click here to Skip to main content
15,890,438 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I would like to write function which give the decimal part of my float number. 
12.56 must return 56; 
90.2547 must return 2547; 
25 must return 0.


What I have tried:

C#
float_number - Math.Truncate(float_number);

But this solution does not return the exact value. 90.2547 can return 254692547. I just want 2547 as result.
Posted
Updated 4-Sep-19 16:32pm
v3

I think It will do the job:
C#
public int GetDecimalPart(float number)
        {
            var decimalNumber = Convert.ToDecimal(number);
            int decimalPart = int.Parse((decimalNumber % 1).ToString().Replace("0.", ""));

            return decimalPart;
        }
 
Share this answer
 
Comments
BillWoodruff 4-Sep-19 22:47pm    
Note that conversion to Decimal is going to round the value.
Nacoumblé Olivier Martial Soro 5-Sep-19 9:10am    
When using Convert.Decimal the value is not rounded. The value is rounded with new Decimal (number).
BillWoodruff 5-Sep-19 17:57pm    
You are incorrect.

decimal dec = Convert.ToDecimal(76790.25476f) // => 76790.26
See this for understanding the limitations of using decimal or float Types to express numeric values: [^].

private const int SIGN_MASK = ~Int32.MinValue;

public int GetDecimalRemainder(float fvalue)
{
    double dplaces;

    try
    {
        decimal dvalue = Convert.ToDecimal(fvalue);

        dplaces = (double) ((Decimal.GetBits(dvalue)[3] & SIGN_MASK) >> 16);

        return (int) ((dvalue - Math.Truncate(dvalue)) * (int) Math.Pow(10d, dplaces));
    }
    catch (Exception ex)
    {
        throw new TypeInitializationException(@"{fvalue} cannot be converted", ex);
    }
}
Notes:

0 note that conversion to decimal may round the value, leading to loss og precision in the mantissa.

1 this will return a negative number if the input float is negative

2 use of 'GetBits to find the number of powers of ten in a float mantissa iis based on: [^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900