解析字符串用逗号和点翻番 [英] Parse strings to double with comma and point

查看:123
本文介绍了解析字符串用逗号和点翻番的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图写一个字符串数组基本上转换为字符串数组,其中阵列中的所有双打都四舍五入到小数位数我设置的数的函数。此外,还可以在阵列中的字符串这根本没有双重价值。

I am trying to write a function which basically converts an array of strings to an array of strings where all the doubles in the array are rounded to the number of decimalplaces i set. There can also be strings in the array which are no double values at all.

string[,] values = new string[1, 3];

values[0, 0] = "hello";
values[0, 1] = "0.123";
values[0, 2] = "0,123";

int decimalPlaces = 2;

double tmp;
string format = "F" + decimalPlaces.ToString();
IFormatProvider provider = CultureInfo.InvariantCulture;
for (int i = 0; i < values.GetLength(0); i++)
{
    for (int j = 0; j < values.GetLength(1); j++)
    {
        if (double.TryParse(values[i, j], out tmp))
        {
            values[i, j] = tmp.ToString(format, provider);
        }
    }
}

Console.ReadLine();

结果却是:你好,0.12,0.12,但它是你好,123.00,0.12将把逗号以错误的方式。有没有人有这样一个简单而有效的解决方案?

The result has to be: "hello" , "0.12", "0.12" but it is "hello", "123.00", "0.12" will treat the comma in the wrong way. Does anyone have a simple and efficient solution for this?

推荐答案

您想治疗点(),如逗号()。因此,替换

You want to treat dot (.) like comma (,). So, replace

if (double.TryParse(values[i, j], out tmp))

if (double.TryParse(values[i, j].Replace('.', ','), out tmp))

这篇关于解析字符串用逗号和点翻番的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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