2

I have tried looking for a similar question here but I can only find how to count the number of decimal places.

What I want to know is: how do I find the value of the decimal places that are >0?

For example, if we have:

decimal value = 1.920m;
decimal value2 = 1.900m;

How do I check if the values after the decimal point are >0?

I want to be able to check this and restrict the display accordingly so I can display something like this:

1.92
1.9
GrandMasterFlush
  • 6,269
  • 19
  • 81
  • 104

3 Answers3

1

Essentially you want to display the value with the max number of decimal places available and remove the trailing zeros. This is the easiest way to do it:

Console.WriteLine(value.ToString("G29")); // Output 1.92

Alternate solution (which works for numbers smaller than 0.00001m unlike the above solution). Though this doesn't look as neat as the previous solution using G29, this works better since it also covers numbers smaller than 0.00001:

Console.WriteLine(value.ToString("0.#############################"));  // Output 1.92

We are using G29 since 29 is the maximum available digits for a decimal. The G or General Format Specifier is used to define the maximum number of significant digits that can appear in the result string. Any trailing zeros are truncated using this format specifier. You can read more about it here.

Input:  1.900m
Output: 1.9

Input:  14.571428571428571428571428571M
Output: 14.571428571428571428571428571

Input:  0.00001000000m
Output: 1E-05 (Using first solution G29)
Output: 0.00001 (Using second solution)
degant
  • 4,861
  • 1
  • 17
  • 29
0

If i understand you right you can do something like this:

double x = 1.92;
x-=(int)x;
while(x%1>0){
   x*=10;
}
Console.WriteLine(x);

output:

92

now you can check what you want on this number

Raz Zelinger
  • 686
  • 9
  • 24
0

If you want to convert to decimal only use this

static decimal? RemoveTrailingZeros(this decimal? value)
{
    if (value == null) return null;

    var format = $"0.{string.Join(string.Empty, Enumerable.Repeat("#", 29))}";
    var strvalue = value.Value.ToString(format);
    return ConvertToDecimalCultureInvariant(strvalue);
}

static decimal? ConvertToDecimalCultureInvariant(this string value)
{
    decimal decValue;

    if (!decimal.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out decValue))
    {
        return null;
    }
    return decValue;
}

Since the precision of a decimal is 29 hence Enumerable.Repeat("#", 29).

And use it as

var result = RemoveTrailingZeros(29.0000m);

enter image description here

Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
  • I did try this first but i was not able to run my program after. I must of implemented it wrong or something. But thank you for time, i appreciate it :) – Charlie Walkden Apr 30 '17 at 11:34