Remove decimal point from a decimal number

前端 未结 7 2132
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-19 01:32

I am trying to remove just the decimal point from a decimal number in C#.

For example:

  • My decimal number is 2353.61 I want 235361
相关标签:
7条回答
  • 2021-01-19 01:44

    I would simply get the number of decimals and multiply it by the correct power of 10. Probably not really a concern but this also would be faster and use less memory then casting it to a string splitting / recombining it, then casting it back to a double. This also works for any number of decimal places.

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

    Using this answer to get the number of decimals.

    0 讨论(0)
  • 2021-01-19 01:45

    Here I have taken decimal value as 1.09, then we take the first index of value with first or default, then you can get value without decimals and without round off.

    var dec = 1.09;
    var op1 = Convert.ToDecimal(dec.ToString().Split('.').FirstOrDefault());
    
    0 讨论(0)
  • 2021-01-19 01:49

    If you always want the printed value to include 2 digits for consistency, you can just multiple by 100 and truncate the result.

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

    This would provide the value you specified in both cases, but also provide a similar result for 2353.6 (-> 235360).

    0 讨论(0)
  • 2021-01-19 01:58

    Here it 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 讨论(0)
  • 2021-01-19 02:02

    Multiply it by ten? You could also use Math.Round(). That will round the number to it's nearest one.

    0 讨论(0)
  • 2021-01-19 02:06

    A simple solution would be:

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

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

    0 讨论(0)
提交回复
热议问题