Reputation: 1587
I'm trying to convert a string that is in the following format: 30,500
to convert to a float as 30.500
(in a json) So currently I have something like float.Parse(string.Format("{0:00,000}", inp_km.Text), CultureInfo.InvariantCulture.NumberFormat)
, but when I save it in json, it saves as 30500.00
.
What am I doing wrong here?
How I just make it;
I make an object from the class Results
like here;
team_results = new Results()
{
team_number = selected_team.team_number,
results = new Result[2] { new Result{ }, new Result { } }
};
Now when I add the new value to the json (example below) the input I get is 30,500
[
{
"team_number": 101,
"results": [
{
"given_start_time": "20:25",
"connection_to_start": "0:00",
"start_kp": "20:26",
"stop_kp": "0:0",
"missed_controls": 0,
"km": 0.000,
"gtks": [ "25:00", "30:15", "0:00" ]
},
{
"given_start_time": "21:56",
"connection_to_start": "0:00",
"start_kp": "21:57",
"stop_kp": "0:0",
"missed_controls": 0,
"km": 0.000,
"gtks": [ "25:00", "30:15" ]
}
]
}
]
But when it saves, it saves it as 30500.00
Upvotes: 1
Views: 499
Reputation: 62213
You are trying to execute Format
on a string which will just yield the same string as a result.
You want to parse the string and pass an IFormatProvider
implementation to the Parse
method that "understands" what ,
and .
mean in the string representation of the number being parsed.
In the example below I used the culture nl-NL
which has the same meaning as what you expect in your question (.
for separating thousands and ,
for separating the fractional part of the number).
const string inputText = "30,500";
var result = float.Parse(inputText, NumberStyles.AllowDecimalPoint, System.Globalization.CultureInfo.GetCultureInfo("nl-NL"));
Console.WriteLine("Parsed {0} to value {1}", inputText, result);
Upvotes: 5
Reputation: 2216
You can create custom NumberFormatInfo
var nf = new System.Globalization.NumberFormatInfo();
nf.NumberDecimalSeparator = ",";
nf.NumberGroupSeparator = " ";
and use it to Parse numeric value
Console.WriteLine(float.Parse("30,5000", nf));
Upvotes: 2
Reputation: 44
Well , I have a solution but it would not be the best but it will work . as you are working on a string you can use this function
string converter(string s)
{
s = s.Replace('.',',');
return s;
}
also check this link https://msdn.microsoft.com/en-us/library/czx8s9ts(v=vs.110).aspx
Upvotes: 0