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

huangapple go评论70阅读模式
英文:

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

问题

我正在使用以下代码将厘米转换为米。

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

当我输入数字 8.8 时,输出结果为

> 0.08800000000000001m

但我想要在十进制部分的零不添加任何值的索引处停止。在这种情况下,我希望显示值为

> 0.088m

这在主要的转换网站上已经实现。当您在谷歌上键入cm转换为m转换器时,这些网站会出现。他们是如何做到的呢?

我尝试了相同的示例并放在他们的网站上,这是它们的显示方式。

> 0.088m

我不能盲目地将值转换为字符串后截取字符串,因为零部分可能出现在第5或第6个元素中。这也在这些网站中处理过了。

这是一个双精度数据类型。字母 "m" 最后一刻连接。如何实现这一点?

英文:

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?

答案1

得分: 3

我会使用decimal而不是double:

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
}

参考链接:https://stackoverflow.com/questions/1165761/decimal-vs-double-which-one-should-i-use-and-when

英文:

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
}

https://stackoverflow.com/questions/1165761/decimal-vs-double-which-one-should-i-use-and-when

huangapple
  • 本文由 发表于 2023年1月8日 22:22:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/75048485.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定