使用Single.TryParse解析浮点数失败 [英] Parsing floats with Single.TryParse fails

查看:277
本文介绍了使用Single.TryParse解析浮点数失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在MSDN上有一篇有关Single.TryParse的文章,其中包含以下示例代码: http://msdn.microsoft.com/en -us/library/26sxas5t%28v = vs.100%29.aspx

There is an article on Single.TryParse over at MSDN with this example code: http://msdn.microsoft.com/en-us/library/26sxas5t%28v=vs.100%29.aspx

// Parse a floating-point value with a thousands separator.
value = "1,643.57";
if (Single.TryParse(value, out number))
    Console.WriteLine(number);
else
    Console.WriteLine("Unable to parse '{0}'.", value);

文章中的问题是TryParse返回true并转换了字符串,但是当我尝试时,它是false.我该如何解决?

Problem is in the article the TryParse returns true and the string is converted, but when I try it, it's false. How do I fix this?

UPD::为简化解析,可以使用以下两行:

UPD: To simplify parsing, these two lines can be used:

NumberStyles style = System.Globalization.NumberStyles.Any;
CultureInfo culture = CultureInfo.InvariantCulture;

此设置允许解析负浮点数和带有前导和尾随空格字符的字符串.

This setting allows for negative floats and strings with leading and trailing space characters to be parsed.

推荐答案

您需要设置文化

using System.Globalization;

string value = "1345,978";
NumberStyles style = System.Globalization.NumberStyles.AllowDecimalPoint;
CultureInfo culture = System.Globalization.CultureInfo.CreateSpecificCulture("fr-FR");
if (Single.TryParse(value, style, culture, out number))
   Console.WriteLine("Converted '{0}' to {1}.", value, number);
else
   Console.WriteLine("Unable to convert '{0}'.", value);

from msdn: Single.TryParse方法(字符串,NumberStyles,IFormatProvider,单个%)

from msdn : Single.TryParse Method (String, NumberStyles, IFormatProvider, Single%)

float usedAmount;
// try parsing with "fr-FR" first
bool success = float.TryParse(inputUsedAmount.Value,
                              NumberStyles.Float | NumberStyles.AllowThousands,
                              CultureInfo.GetCultureInfo("fr-FR"),
                              out usedAmount);

if (!success)
{
    // parsing with "fr-FR" failed so try parsing with InvariantCulture
    success = float.TryParse(inputUsedAmount.Value,
                             NumberStyles.Float | NumberStyles.AllowThousands,
                             CultureInfo.InvariantCulture,
                             out usedAmount);
}

if (!success)
{
    // parsing failed with both "fr-FR" and InvariantCulture
}

在此处回答: C#float.tryparse用于法国文化

这篇关于使用Single.TryParse解析浮点数失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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