Home > Enterprise >  How to Find the number zero in decimal part where add no value to the number and remove that part
How to Find the number zero in decimal part where add no value to the number and remove that part

Time:01-09

I am using the following code to convert cm to the meter.

 public static double? ConvertCmToM(double? cm)
        {
            return cm.Value * 0.01;
            
        }

When I input the number 8.8 output giving as

0.08800000000000001m

But I want to stop in the index where zero adds no value in the decimal part. In this case I want to display the value as

0.088m

This is already done in major converter websites. when you type the cm to m converter on google those sites will appear. How do they do it?

I took the same sample and put in their sites and this is how they show.

> 0.088m

I cannot blindly substring the value after converting to a string as the zero part will appear in 5th or 6th element. That also handled in those sites.

This is a double data type. the letter "m" concat at the last minute. How to acehive this?

CodePudding user response:

I would use decimal instead of double then:

public static decimal? ConvertCmToM(decimal? cm)
{
    if(cm == null) return null;
    return Decimal.Multiply(cm.Value, 0.01m);
}

static void Main()
{
    Console.Write(ConvertCmToM(8.8m)); // 0.088
}

decimal vs double! - Which one should I use and when?

  • Related