C# parse int from different locale [duplicate] - c#

This question already has answers here:
Thousand separated value to integer
(4 answers)
Closed 3 years ago.
I know, there are other questions like this
e.g. Convert number into culture specific
But I am having a hard time and even the answer doesn't work for me. Still getting
System.FormatException: 'Input string was not in a correct format.'
My current/system locale is de and I am parsing an en int. Whatever I tried so far (including answers from previous quesions, does not work.
So, what am I missing?
string numberStr = "1,111"; // one thousand one hundred eleven
//int result = int.Parse(numberStr);
//int result = int.Parse(numberStr, CultureInfo.GetCultureInfo("en-US").NumberFormat);
//int result = int.Parse(numberStr, CultureInfo.InvariantCulture);
//int result = int.Parse(numberStr, CultureInfo.InvariantCulture.NumberFormat);
//int result = int.Parse(numberStr, CultureInfo.GetCultureInfo("en-UK").NumberFormat);
int result = int.Parse(numberStr, CultureInfo.GetCultureInfo("en"));
Console.WriteLine(result);

Your problem is simply that int.Parse(string) and int.Parse(string, IFormatProvider) don't allow a thousands separator.
You can see this in the Remarks section of the doc:
The s parameter contains a number of the form:
[ws][sign]digits[ws]
You can however, use the int.Parse(string, NumberStyles), overload, which lets you specify NumberStyles.
If we peek at the source for int.Parse(string), we can see that it effectively calls int.Parse(string, NumberStyles.Integer).
If you look at the docs for NumberStyles, we want Integer, but also AllowThousands. We don't want to go as far as Number, because that includes AllowDecimalPoint, and integers can't have decimal points.
int result = int.Parse("1,111", NumberStyles.Integer | NumberStyles.AllowThousands);
You probably also want to specify a culture, because the thousands separator depends on culture (e.g. German uses . as the thousands separator). The invariant culture uses ,, as does en:
int result = int.Parse(
"1,111",
NumberStyles.Integer | NumberStyles.AllowThousands,
CultureInfo.InvariantCulture);

If you allow thousands separators, it will work:
int.Parse("1,111", NumberStyles.AllowThousands, CultureInfo.GetCultureInfo("en"));
// 1111

Related

Formatting decimal numbers in C#

How can I transform these numbers
Examples:
77.0227
0.0803
1.1567
Into these numbers respectively:
77,02
8,03
1,16
This all needs to be done with the same "formatting".
These values come from a stored Procedure in SQL , and they are always different, but they need to be in the correct format. They are all Percent Values.
You can use the fixed-point ("F") format specifier to round to two digits:
decimal number = 77.0227m;
string result = number.ToString("F2");
If this doesn't give you the desired format(no commas but dots for example), then you have to pass the desired culture. Presuming you want spanish:
var spanishCulture = new CultureInfo("es-ES");
string result = number.ToString("F2", spanishCulture);
If you need commas as decimal separator you should need to specify the culture; like this:
string result = string.Format(new System.Globalization.CultureInfo("es-ES"), "{0:#,##0.00}", inputValue);
I'm supposing Spain's culture (Spanish language), so trying with that code.
See a running example in this fiddle.

How to check values numbers after the decimal point [duplicate]

This question already has answers here:
Remove trailing zeros
(23 answers)
Closed 5 years ago.
I have tried looking for a similar question here but I can only find how to count the number of decimal places.
What I want to know is: how do I find the value of the decimal places that are >0?
For example, if we have:
decimal value = 1.920m;
decimal value2 = 1.900m;
How do I check if the values after the decimal point are >0?
I want to be able to check this and restrict the display accordingly so I can display something like this:
1.92
1.9
Essentially you want to display the value with the max number of decimal places available and remove the trailing zeros. This is the easiest way to do it:
Console.WriteLine(value.ToString("G29")); // Output 1.92
Alternate solution (which works for numbers smaller than 0.00001m unlike the above solution). Though this doesn't look as neat as the previous solution using G29, this works better since it also covers numbers smaller than 0.00001:
Console.WriteLine(value.ToString("0.#############################")); // Output 1.92
We are using G29 since 29 is the maximum available digits for a decimal. The G or General Format Specifier is used to define the maximum number of significant digits that can appear in the result string. Any trailing zeros are truncated using this format specifier. You can read more about it here.
Input: 1.900m
Output: 1.9
Input: 14.571428571428571428571428571M
Output: 14.571428571428571428571428571
Input: 0.00001000000m
Output: 1E-05 (Using first solution G29)
Output: 0.00001 (Using second solution)
If i understand you right you can do something like this:
double x = 1.92;
x-=(int)x;
while(x%1>0){
x*=10;
}
Console.WriteLine(x);
output:
92
now you can check what you want on this number
If you want to convert to decimal only use this
static decimal? RemoveTrailingZeros(this decimal? value)
{
if (value == null) return null;
var format = $"0.{string.Join(string.Empty, Enumerable.Repeat("#", 29))}";
var strvalue = value.Value.ToString(format);
return ConvertToDecimalCultureInvariant(strvalue);
}
static decimal? ConvertToDecimalCultureInvariant(this string value)
{
decimal decValue;
if (!decimal.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out decValue))
{
return null;
}
return decValue;
}
Since the precision of a decimal is 29 hence Enumerable.Repeat("#", 29).
And use it as
var result = RemoveTrailingZeros(29.0000m);

How to convert a number to a string but formatted with x number of digits [duplicate]

This question already has answers here:
Format string to a 3 digit number
(9 answers)
Closed 8 years ago.
I want to convert a number to a string but have the number formatted with 10 digits. For example, if the number is 5, the string should be "0000000005". I checked the formatting of strings at:
http://msdn.microsoft.com/en-us/library/0c899ak8(v=vs.110).aspx
but there isn't any format that lets you specify the number of digits.
Actually the "0" placeholder would work but in reality I need 100 places, so I'm not going to use the "0" placeholder.
You can use the ToString formatting Dn to output leading zeroes:
var d = 5;
var s2 = d.ToString("D2");
var s10 = d.ToString("D10");
Console.WriteLine(s2);
Console.WriteLine(s10);
The output is:
05
0000000005
Normally the D specifier for standard numeric format strings is enough with its precision to format a number with the required number of leading zeros.
But it stops at 99 and if you really need 100 leading zeros you need to resort to the old trusty method of string concatenation and right truncation
int number = 5;
string leadingZero = new string ('0', 100) + number.ToString();
string result = leadingZero.Substring(leadingZero.Length - 100);
This page should help you find the solution you need: http://msdn.microsoft.com/en-us/library/dd260048(v=vs.110).aspx

How to round and format a decimal correctly? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
c# - How do I round a decimal value to 2 decimal places (for output on a page)
I'm trying to get my decimals to display with four decimal places. The DB rounds my number to 4 decimal places, but it returns the number with trailing 0s (due to the decimal precision of the field), so something like 9.45670000. Then, when I do this:
string.Format("{0:#,#.####}", decimalValue);
The output I get on the page is 9.4567, which is what I want.
However, if the number returned from DB is 9.45600000, the output after doing the format is 9.456
But what I need to display is 9.4560
How do I format my decimal, so that the number of decimal places is always four?
UPDATE: Also, is it possible to use a variable (instead of .0000) if I wanted the number of decimal places to be determined dynamically?
string.Format("{0:N4}",decimalValue);
Standard Numeric Format Strings
Custom Numeric Format Strings
To set the precision dynamically you can do the following:
double value = 9.4560000;
int precision = 4;
string format = String.Format("{{0:N{0}}}",precision);
string valuestring = String.Format(format, value);
string.Format({0:#,#0.0000}, decimalValue);
Use String.Format -
decimal d =123.47
string specifier="{0:0,0.0000}"; // You need to get specifier dynamically here..
String.Format(specifier, d); // "123.4700"
Try this:
string.Format("{0:#,###.0000}", 9.45600000);
Adding the zeroes in the format forces a zero to be output if there is not a digit to put there.
To add the zeroes with the number of zeroes driven programmatically you could do this:
int x = 5;
string fmt = "{0:#,###." + new string('0', x) + "}";
string.Format(fmt, 9.456000000);

Parsing a string

I want to parse a string to long the value is 1.0010412473392E+15.But it gives a exception input string was not in a correct format.how to do this.
Both these answers work how to select both of them as answer.
Check out the System.Globalization.NumberStyles enumeration in the appropriate overload of Int64.Parse. If you specify System.Globalization.NumberStyles.Any, it should work:
long v = Int64.Parse(s, System.Globalization.NumberStyles.Any);
Note, however that the number you are parsing has limited precision, (there are only 13 decimal places but is specified as E+15). Also, the 'Any' enumeration is probably more than you really need - in this case you only need AllowDecimalPoint and AllowExponent:
long v = Int64.Parse(s, System.Globalization.NumberStyles.AllowDecimalPoint | System.Globalization.NumberStyles.AllowExponent);
Are you sure you don't want to parse to double?
var myDouble = double.Parse(myString);
You can then try converting to long.
var myLong = Convert.ToInt64(myDouble);

Categories

Resources