Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
852 views
in Technique[技术] by (71.8m points)

c# - How to make InvariantCulture recognize a comma as a decimal separator?

How do I parse 1,2 with Single.Parse? The reason of asking is because, when I am using CultureInfo.InvariantCulture I don't get 1.2 as I would like, but rather 12.

Shouldn't "Invariant Culture" ignore the culture?

Consider the following example:

using System;
using System.Globalization;

public class Program
{
    public static void Main()
    {
        Console.WriteLine(Single.Parse("1,2", CultureInfo.InvariantCulture));
        Console.WriteLine(Single.Parse("1.2", CultureInfo.InvariantCulture));
        float value;
        Console.WriteLine(Single.TryParse("1,2", NumberStyles.Float, CultureInfo.InvariantCulture, out value));
        Console.WriteLine(Single.TryParse("1,2", out value));
        Console.WriteLine(value);
    }
}

The output of this will be

12
1.2
False
True
12

But I was expecting:

1.2
1.2
True
True
1.2

Based on my reading of InvariantCulture I should get that result, however I am not.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

CultureInfo.InvariantCulture uses . as a decimal separator, and , as a thousands separator. This is independent of any user settings, and independent of the string you've got, hence the name "InvariantCulture". The specific details are listed on the NumberFormatInfo.InvariantInfo MSDN page.

To use , as the decimal separator, don't use CultureInfo.InvariantCulture. Instead, use a culture that does use , as the decimal separator. There are many that would suit your needs.

Alternatively, create a custom culture based on CultureInfo.InvariantCulture. You can call its Clone method to create a copy of which you can modify the properties.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...