How to remove a decimal point from a decimal number in C #?

Am I trying to remove only a decimal point from a decimal in C #?

For example: my decimal is 2353.61. As a result, I want to get 235361. My decimal number is 196.06. I want a result in 1960.

How can i do this?

+4
source share
6 answers

I would just get the number of decimal places and multiply it by the correct power of 10. Probably not a problem, but it would also be faster and use less memory and then flip it to a string, splitting / recombining it, and then throwing it back to double. This also works for any number of decimal places.

decimal d = 2353.61;
int count = BitConverter.GetBytes(decimal.GetBits(d)[3])[2];
d *= Math.pow(10, count);

, .

+6

, - ( - ):

string str = decNum.ToString().Replace(".",string.Empty);
decimal dec = decimal.Parse(str);
+1

, 2 , 100 .

value = Math.Truncate(value * 100m);

, , 2353.6 (- > 235360).

0

?:-) Math.Round(). .

0
source

There he is:

    public decimal RemoveDecimalPoints(decimal d)
    {
        try
        {
            return d * Convert.ToDecimal(Math.Pow(10, (double)BitConverter.GetBytes(decimal.GetBits(d)[3])[2]));
        }
        catch (OverflowException up)
        {
            // unable to convert double to decimal
            throw up; // haha
        }
    }
0
source

A simple solution:

while((int)n != n) n *= 10;

Multiplying a number by 10 moves the decimal point 1 to the right. You need to repeat this multiplication until there are no more numbers on the right side. To determine if there are more numbers on the right, you simply throw it on int, which discards the decimal part.

0
source

All Articles