问题描述
我在数据库中有两个 nvarchar 字段来存储 DataType 和 DefaultValue,我有一个 DataType Double 和值为 65.89875 的英文格式.
I have two nvarchar fields in a database to store the DataType and DefaultValue, and I have a DataType Double and value as 65.89875 in English format.
现在我希望用户根据选择的浏览器语言格式查看值(英语中的 65.89875 应显示为德语中的 65,89875).现在,如果用户从德语格式编辑为 65,89875,相当于英语中的 65.89875,而其他用户从英文浏览器查看,则为 6589875.
Now I want the user to see the value as per the selected browser language format (65.89875 in English should be displayed as 65,89875 in German). Now if the user edits from German format to 65,89875 which is 65.89875 equivalent in English, and the other user views from an English browser it comes as 6589875.
发生这种情况是因为在数据库中它在 nvarchar 列中存储为 65,89875,当使用英语文化转换时,它变为 6589875,因为它将 ,
视为分隔符,这是德语的小数运算符.
This happens because in the database it was stored as 65,89875 in the nvarchar column and when converted using English culture it becomes 6589875 since it considers ,
as a separator which is a decimal operator for German.
如何让它适用于所有浏览器?
How do I get this working for all the browsers?
推荐答案
您需要为存储在数据库中的数据定义一个区域设置,不变的文化就是为了这个目的.
You need to define a single locale that you will use for the data stored in the database, the invariant culture is there for exactly this purpose.
当你显示转换为本机类型,然后为用户的文化格式化.
When you display convert to the native type and then format for the user's culture.
例如显示:
string fromDb = "123.56";
string display = double.Parse(fromDb, CultureInfo.InvariantCulture).ToString(userCulture);
存储:
string fromUser = "132,56";
double value;
// Probably want to use a more specific NumberStyles selection here.
if (!double.TryParse(fromUser, NumberStyles.Any, userCulture, out value)) {
// Error...
}
string forDB = value.ToString(CultureInfo.InvariantCulture);
PS.几乎不用说,使用具有与数据匹配的数据类型的列会更好(但有时也适用于旧版).
PS. It, almost, goes without saying that using a column with a datatype that matches the data would be even better (but sometimes legacy applies).
这篇关于如何使用适当的文化信息将字符串转换为双精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!