String position with "," to double with "." - c#

I am trying to convert a position from a string to double , to use it on map.
The string position is in the format like:
latString: "31,92002306867021"
Using:
double lat = Convert.ToDouble(latString, CultureInfo.InvariantCulture);
the result is wrong : 3,19200230686702E+15
Using Convert.ToDouble(latString) give me number without "."
What is the right way to manage that type of convertion?

The invariant culture is associated with the English culture and thus uses . as a decimal separator. The , will be interpreted as a thousands separator.
If you pass in a culture that uses commas (e.g. nl-NL), it will work:
double lat = Convert.ToDouble("31,1234", CultureInfo.CreateSpecificCulture("nl-NL"));
If you are absolutely certain the input strings can only contain valid latitudes/longitudes (i.e. numbers will never exceed 1,000), then you could also use string replacement:
double lat = Convert.ToDouble("31,1234".Replace(',', '.'), CultureInfo.InvariantCulture);

It seems that you have latString in some different culture that uses , as a thousand separator which is just ignored while converting to floating point:
"31,92002306867021" -> 3192002306867021 -> 3.19200230686702E+15
First, check your current culture, it may well appear that it uses , as a decimal separator:
string latString = "31,92002306867021";
// Current culture
double result = Convert.ToDouble(latString);
If not, you can try to replace , with a current decimal separator:
string latString = "31,92002306867021";
// be careful and culture specific: naive
// latString.Replace(",", ".")
// will cause problems with some cultures
// (e.g. ru-Ru which uses "." as a thousand separator)
string value = latString.Replace(",",
CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);
double result = Convert.ToDouble(value);

Related

string format money , [duplicate]

I need to display a number with commas and a decimal point.
Eg:
Case 1 : Decimal number is 432324 (This does not have commas or decimal points).
Need to display it as: 432,324.00.
Not: 432,324
Case 2 : Decimal number is 2222222.22 (This does not have commas).
Need to display it as: 2,222,222.22
I tried ToString("#,##0.##"), but it is not formatting it correctly.
int number = 1234567890;
number.ToString("#,##0.00");
You will get the result 1,234,567,890.00.
Maybe you simply want the standard format string "N", as in
number.ToString("N")
It will use thousand separators, and a fixed number of fractional decimals. The symbol for thousands separators and the symbol for the decimal point depend on the format provider (typically CultureInfo) you use, as does the number of decimals (which will normally by 2, as you require).
If the format provider specifies a different number of decimals, and if you don't want to change the format provider, you can give the number of decimals after the N, as in .ToString("N2").
Edit: The sizes of the groups between the commas are governed by the
CultureInfo.CurrentCulture.NumberFormat.NumberGroupSizes
array, given that you don't specify a special format provider.
Try with
ToString("#,##0.00")
From MSDN
*The "0" custom format specifier serves as a zero-placeholder symbol. If the value that is being formatted has a digit in the position where the zero appears in the format string, that digit is copied to the result string; otherwise, a zero appears in the result string. The position of the leftmost zero before the decimal point and the rightmost zero after the decimal point determines the range of digits that are always present in the result string.
The "00" specifier causes the value to be rounded to the nearest digit preceding the decimal, where rounding away from zero is always used. For example, formatting 34.5 with "00" would result in the value 35.*
I had the same problem. I wanted to format numbers like the "General" format in spreadsheets, meaning show decimals if they're significant, but chop them off if not. In other words:
1234.56 => 1,234.56
1234 => 1,234
It needs to support a maximum number of places after the decimal, but don't put trailing zeros or dots if not required, and of course, it needs to be culture friendly. I never really figured out a clean way to do it using String.Format alone, but a combination of String.Format and Regex.Replace with some culture help from NumberFormatInfo.CurrentInfo did the job (LinqPad C# Program).
string FormatNumber<T>(T number, int maxDecimals = 4) {
return Regex.Replace(String.Format("{0:n" + maxDecimals + "}", number),
#"[" + System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator + "]?0+$", "");
}
void Main(){
foreach (var test in new[] { 123, 1234, 1234.56, 123456.789, 1234.56789123 } )
Console.WriteLine(test + " = " + FormatNumber(test));
}
Produces:
123 = 123
1234 = 1,234
1234.56 = 1,234.56
123456.789 = 123,456.789
1234.56789123 = 1,234.5679
Try with
ToString("#,##0.###")
Produces:
1234.55678 => 1,234.556
1234 => 1,234
For Razor View:
$#string.Format("{0:#,0.00}",item.TotalAmount)
CultureInfo us = new CultureInfo("en-US");
TotalAmount.ToString("N", us)
Your question is not very clear but this should achieve what you are trying to do:
decimal numericValue = 3494309432324.00m;
string formatted = numericValue.ToString("#,##0.00");
Then formatted will contain: 3,494,309,432,324.00
All that is needed is "#,0.00", c# does the rest.
Num.ToString("#,0.00"")
The "#,0" formats the thousand separators
"0.00" forces two decimal points
If you are using string variables you can format the string directly using a : then specify the format (e.g. N0, P2, etc).
decimal Number = 2000.55512016465m;
$"{Number:N}" #Outputs 2,000.55512016465
You can also specify the number of decimal places to show by adding a number to the end like
$"{Number:N1}" #Outputs 2,000.5
$"{Number:N2}" #Outputs 2,000.55
$"{Number:N3}" #Outputs 2,000.555
$"{Number:N4}" #Outputs 2,000.5551
string Mynewcurrency = DisplayIndianCurrency("7743450.00");
private string DisplayIndianCurrency(string EXruppesformate)
{
string fare = EXruppesformate;
decimal parsed = decimal.Parse(fare, CultureInfo.InvariantCulture);
CultureInfo hindi = new CultureInfo("en-IN");
// string text = string.Format(hindi, "{0:c}", parsed);if you want <b>Rs 77,43,450.00</b>
string text = string.Format(hindi, "{0:N}", parsed); //if you want <b>77,43,450.00</b>
return ruppesformate = text;
}
For anyone looking at this now, and getting the "No overload for method 'ToString' takes 1 argument" when using:
TotalNumber.ToString("N")
My solution has been to use :
TotalNumber.Value.ToString("N")
I often get stuck on this when working directly inside an MVC View, the following wasn't working:
#Model.Sum(x => x.Number).ToString("N")
Whereas this works:
#Model.Sum(x => x.Number).Value.ToString("N")

Remove trailing zeros and thousand separator (comma)

Since I am using this to remove trailing zeros when there is no value behind decimal:
decimal.Parse(variable).ToString("G29")
But it doesn't give thousand separator. For example:
string amount = "54321.00"
string amount2 = "54321.55"
string parsed = decimal.Parse(amount).ToString("G29");
string parsed2 = decimal.Parse(amount2).ToString("G29");
//parsed = 54321
//parsed2 = 54321.55
//my goal
//parsed = 54,321
//parsed2 = 54,321.55
Is there any better format type?
Use a custom format
string format = "#,#.##";
decimal noDecimalPlaces = 54321.00m;
decimal decimalPlaces = 54321.55m;
Console.WriteLine(noDecimalPlaces.ToString(format)); // writes 54,321
Console.WriteLine(decimalPlaces.ToString(format)); // writes 54,321.55
You can read more about formatting decimals on msdn.
The way this works
The latter part .## specifies that you allow up to two decimal places. The former part #,# specifies that you want to separate the integer part of your value.
Note:
The number formatting is still culture specific, so for cultures that use , as the decimal separator and . for digit grouping your numbers will be displayed as 54.321 and 54.321,55 instead. You can find out more about formatting in .NET here.

Strange output when converting string to double

I already searched for my problem but I wasn't successfully and that's the reason I'm here.
All I want to do is reading a string like "3.14" and convert it to double.
Enough said... here is my code:
using System;
namespace GlazerCalcApplication
{
class MainClass
{
public static void Main (string[] args)
{
string heightString;
double height;
heightString = Console.ReadLine();
height = Convert.ToDouble(heightString);
Console.WriteLine(height);
}
}
}
Output:
3.14
314
Press any key to continue...
Why is my double value not 3.14?
Instead of Convert.ToDouble() I also tried it with double.Parse() but I received the same behaviour. Reading strings like 3,14 is no problem.
Maybe I should also mention that I use MonoDevelop and a linux OS.
Thanks in advance.
Try specifying the culture as Invariant:
height = Convert.ToDouble(heightString,CultureInfo.InvariantCulture);
It seems the decimal seperator of your culture is comma instead of dot therefore dot is truncated after conversion.
Convert.ToDouble(string) uses Double.Parse(string, CultureInfo.CurrentCulture) method explicitly.
Here how it's implemented;
public static double ToDouble(String value) {
if (value == null)
return 0;
return Double.Parse(value, CultureInfo.CurrentCulture);
}
It is likely your CurrentCulture's NumberFormatInfo.NumberDecimalSeparator property is not . (dot). That's why you can't parse a string with . as a date seperator.
Example in LINQPad;
CultureInfo c = new CultureInfo("de-DE");
c.NumberFormat.NumberDecimalSeparator.Dump(); // Prints ,
As a solution, you can create a new reference of your CurrentCulture and assing it's NumberDecimalSeparator property to . like;
double height;
CultureInfo c = new CultureInfo("de-DE");
c.NumberFormat.NumberDecimalSeparator = ".";
height = Convert.ToDouble("3.14", c);
Judging by the result I take it you are in a culture zone where comma is the normal decimal separator.
Also, I take it that you want both dot and comma to be used for decimal separation.
If not, the below is not the proper solution.
The fastest solution for using both would be
height = Convert.ToDouble(heightString.Replace('.', ',');
This would mean that both dots and comma's are used as comma and thus parsed as a decimal separator.
If you only want to use a dot as separator, you can use invariantculture or a specific numberformatinfo. Invariant culture is already shown in the other posts. numberformat info example:
var nfi = new NumberFormatInfo { NumberDecimalSeparator = "." };
height = double.Parse(heightString,nfi);
For completeness, the example below shows both using numberformatinfo for setting the dot as decimal separator, as well as replacing comma with dots, so both characters are used for decimals
var nfi = new NumberFormatInfo { NumberDecimalSeparator = "." };
height = double.Parse(heightString.Replace(',', '.'),nfi);
Different .Net cultures (countries) have different decimal separators.
If you expect input values to be in some specific format - either use some particular culture or InvariantCulture. Also consider using double.Parse as it geve more flexibility on parsing the values than generic Convert.ToDouble.
var d = double.Parse(heightString, CultureInfo.InvariantCulture);
If you expect user to enter value in local format - your code is fine, but either your expectation of "local format" is wrong, or "current culture" set incorrectly.

Convert a string number with comma to a culture specific double number

NumberFormatInfo numberInfo = CultureInfo.CurrentCulture.NumberFormat;
double result = Convert.ToDouble("2,75", numberInfo);
result = 2.75
My current UI/culture is "de-DE".
Why don't i get 2,75 ?
Because you are not getting a string result, but a double. How you then display that double later is not influenced by your code above.
If you want to see "2,75" on your screen, you need to format the double as a string, adding numberInfo.
Try this to get 2,75:-
string.Format(System.Globalization.CultureInfo.GetCultureInfo("de-DE"), "{0:0.0}", 2.75);
or you can also try this:-
NumberFormatInfo n= new NumberFormatInfo();
n.NumberDecimalSeparator = ",";
n.NumberGroupSeparator = ".";
double d= 2.75;
string s= d.ToString(n); //2,75
You get 2.75. It's only different ways of displaying the number.
The double value contains no information about formatting. It's neither 2.75 nor 2,75, it's just a numeric value.
If you display the number using a culture that uses a comma as decimal separator, you will get what you expect, for example:
Console.WriteLine(result.ToString(CultureInfo.GetCultureInfo(1053)));
Output:
2,75

Double.TryParse() input decimal separator different than system decimal separator

I have a source XML that uses a dot (".") as a decimal separator and I am parsing this on a system that uses a comma (",") as a decimal separator.
As a result, value of 0.7 gets parsed with Double.TryParse or Double.Parse as 7000000.
What are my options to parse correctly? One of them is to replace dots in source with commas with String.Replace('.', ',') but I don't think I like this very much.
XML standard is explicit about the formatting of dates and numbers etc. This helps to ensure that the XML is platform independent and interoperable. Take a look at using XmlConvert for xml data.
double value = XmlConvert.ToDouble(stringValue);
This does the job:
string test = "0.7";
Assert.Equal(0.7, Double.Parse(test, NumberStyles.Float, CultureInfo.InvariantCulture));
double.TryParsehas an overload taking an IFormatProvider. Use a coresponding CultureInfo, in your case CultureInfo.InvariantCulture can be used.
Easy way to specify custom decimal separator:
var price = "122$00";
var nfi = new NumberFormatInfo { CurrencyDecimalSeparator = "$" };
var ok = decimal.TryParse(price, NumberStyles.Currency, nfi, out result);

Categories