删除尾随零 [英] Remove trailing zeros

查看:208
本文介绍了删除尾随零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个集合作为

2.4200
2.0044
2.0000

我要像

2.42
2.0044
2

我试着用的String.Format ,但它返回 2.0000 键,将其设置为 N0 舍入其它值。

I tried with String.Format, but it returns 2.0000 and setting it to N0 rounds the other values as well.

推荐答案

这难道不是如此简单,如果输入的是一个字符串?您可以使用其中的一个:

Is it not as simple as this, if the input IS a string? You can use one of these:

string.Format("{0:G29}", decimal.Parse("2.0044"))

decimal.Parse("2.0044").ToString("G29")

2.0m.ToString("G29")

这应该适用于所有的输入。

This should work for all input.

更新查看标准数字格式我'已经有明确设置precision说明29的文档明确规定:

Update Check out the Standard Numeric Formats I've had to explicitly set the precision specifier to 29 as the docs clearly state:

但是,如果数字是一个小数和precision说明省略,定点符号总是使用和尾随零是preserved

However, if the number is a Decimal and the precision specifier is omitted, fixed-point notation is always used and trailing zeros are preserved

更新 康拉德 <一href="http://stackoverflow.com/questions/4525854/remove-trailing-zeros/4525896#comment-8733932">pointed出的评论:

观察下面0.000001值。 G29格式present他们在最短的方式,因此将切换到该指数符号。 的String.Format({0:G29},decimal.Parse(0.00000001,System.Globalization.CultureInfo.GetCultureInfo(EN-US)))将给予1E-08作为结果。

Watch out for values like 0.000001. G29 format will present them in the shortest possible way so it will switch to the exponential notation. string.Format("{0:G29}", decimal.Parse("0.00000001",System.Globalization.CultureInfo.GetCultureInfo("en-US"))) will give "1E-08" as the result.

这篇关于删除尾随零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆