我怎样可以去除零和小数点了十进制的? [英] How can I strip zeros and decimal points off of decimal strings?

查看:145
本文介绍了我怎样可以去除零和小数点了十进制的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码目前输出:

  12.1 
12.100
12.1000
$ 12.00 12.0000

我怎样才能改变它,所以它输出>

  12.1 
12.1
12.1
12
12
12

Math.Round似乎是一回事,但它让我定义我多少小数想要的,但我想它们是可变如上



如果有这样做没有数学方式,我就剥去零和小数点关琴弦的右侧, 。但会觉得有一种数学方法来处理这个

 使用系统; 
使用System.Collections.Generic;

命名空间Test8834234
{
公共类节目
{
静态无效的主要(字串[] args)
{

文件清单<串GT; decimalsAsStrings =新的List<串GT;
{
12.1,
12.100,
12.1000,
12.00,
12,
12.0000
};

的foreach(在decimalsAsStrings VAR decimalAsString)
{
十进制DEC = decimal.Parse(decimalAsString);
Console.WriteLine(DEC);
}

到Console.ReadLine();

}
}
}


解决方案

您也可以使用十进制的ToString带有参数:

 字符串s = dec.ToString( 0#); 

请注意:您可能必须与您的代码的国际化问题。你有编码的方式,将使用从用户的计算机文化信息,这可能比以外的东西。的小数点分隔符。这可能会导致你的程序给出不正确的结果对于已千位分隔符。



如果你想给用户保证解析方法将始终具有相同的行为,你可以使用 CultureInfo.InvariantCulture 。如果你真的想根据用户的区域性设置,你在做什么是好的解析字符串。


The following code currently outputs:

12.1
12.100
12.1000
12.00
12
12.0000

How can I change it so it outputs:

12.1
12.1
12.1
12
12
12

Math.Round seems to be the thing, but it makes me define how many decimal places I want, but I want them to be variable as above.

If there is no mathematical way to do it, I'll just strip the zeros and decimal points off the right side of the strings, but would think there is a math way to handle this.

using System;
using System.Collections.Generic;

namespace Test8834234
{
    public class Program
    {
        static void Main(string[] args)
        {

            List<string> decimalsAsStrings = new List<string>
            {
                "12.1",
                "12.100",
                "12.1000",
                "12.00",
                "12",
                "12.0000"
            };

            foreach (var decimalAsString in decimalsAsStrings)
            {
                decimal dec = decimal.Parse(decimalAsString);
                Console.WriteLine(dec);
            }

            Console.ReadLine();

        }
    }
}

解决方案

You can also use decimal's ToString with a parameter:

string s = dec.ToString("0.#");

Note: You may have an internationalization issue with your code. The way you have coded it, it will use the culture info from the user's computer, which may have something other than . for the decimal separator. This might cause your program to give incorrect results for users that have . for thousands separator.

If you want to guarantee that the parse method will always behave the same, you could use CultureInfo.InvariantCulture. If you do actually want to parse the string according to the user's culture settings, what you are doing is fine.

这篇关于我怎样可以去除零和小数点了十进制的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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