Would there be a better way of doing this? - c#

post.Min.ToString("0.00").Replace(",", ".").Replace(".00", string.Empty)
post.Min is a double such as 12,34 or 12,00. Expected output is 12.34 or 12.
I basically want to replace the comma by a point, and cut the .00 part if any.
I am asking because I couldn't find anything, or because I don't exactly know what to search. This has an high change of being a duplicate, I simply can't find it. Please let me know.

The simplest solution would appear to be to use CultureInfo.InvariantCulture, and I reject the suggestion that this is any more complicated than using a series of replaces as you demonstrated in your question.
post.Min.ToString("0.##", CultureInfo.InvariantCulture);
# is the digit placeholder, described as the docs like this:
Replaces the "#" symbol with the corresponding digit if one is present; otherwise, no digit appears in the result string.
Try it online
If you use this in a lot of places, and that's why you want to keep it simple, you could make an extension method:
public static class MyExtensions
{
public static string ToHappyString(this double value)
{
return value.ToString("0.##", CultureInfo.InvariantCulture);
}
}
And then you just have to call .ToHappyString() wherever you use it. For example, post.Min.ToHappyString()

You can use .ToString("0.##").
like,
// Considered german culture; May be this is your current culture
CultureInfo culture = new CultureInfo("de");
double number1 = Double.Parse("12,34", culture);
double number2 = Double.Parse("12,00", culture);
Console.WriteLine(number1.ToString("0.##"));
Console.WriteLine(number2.ToString("0.##"));
Output:
12.34
12
.Net fiddle

Checkout the ToString overloads article on MSDN about examples of the N format. This is also covered in the Standard Numeric Format Strings article.
Relevant examples:
// Formatting of 1054.32179:
// N: 1,054.32
// N0: 1,054
// N1: 1,054.3
// N2: 1,054.32
// N3: 1,054.322
For the dot instead of comma to do it properly, in combination with N0 use:
System.Globalization.CultureInfo customCulture = (System.Globalization.CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone();
customCulture.NumberFormat.NumberDecimalSeparator = ".";
System.Threading.Thread.CurrentThread.CurrentCulture = customCulture;

double.ToString("0.##") to consider decimal places only if not .00 and you can create your own Number Format without using Culture:
NumberFormatInfo nfi = new NumberFormatInfo();
nfi.NumberDecimalSeparator = ".";
post.Min.ToString("0.##", nfi);

Related

C# - Using NumberFormatInfo with Convert.ToDouble to return double

In my application I have internationalization and so we have a bunch of methods to deal with formatting.
One of them should receive a double and format it to two decimal places and return a double. For doing so, we are using NumberFormatInfo according to the culture selected.
The problem is I cant get Convert.ToDouble to work with NumberFormatInfo the way I would like to. Basically what I want to know is why this:
using System;
using System.Globalization;
public class Program
{
public static void Main()
{
var myDouble = 9.983743;
var nfi = new NumberFormatInfo() {
NumberDecimalDigits = 2
};
Console.WriteLine("Original value: " + myDouble);
Console.WriteLine("Converted value: " + Convert.ToDouble(myDouble, nfi));
}
}
Prints
Original value: 9.983743
Converted value: 9.983743 // Should be 9.98
And how can I get the result I want using NumberFormatInfo only, if possible.
Thanks,
From MSDN:
The NumberDecimalDigits property is used with the "F" and "N" standard format strings without a precision specifier in numeric formatting operations.
The default is the generic formatting (G). So this will give you the desired result:
Console.WriteLine(myDouble.ToString("N", nfi));
However, 2 is the default value anyway. And it is better to specify it explicitly:
Console.WriteLine(myDouble.ToString("N2", NumberFormatInfo.InvariantInfo));
Update:
Yeah but I do need to return a double from my method.
Now I see. In your place I would return the original double in that case, too. If the consumer of your API wants to display/store it as a string with two digits, then it is his responsibility to format it.
If you really want to omit the last digits of the precision and return a modified value, then use Math.Round instead (but I would not recommend that).
Converting a double to a double does not change anything, a double is always double precision, you cannot change the number of decimal digits.
A double has no format, format comes into play when you display a double by using the ToString() method as explained by taffer.
You can round it down to set all digits after the first 2 to zero, but you cannot remove digits.
You state you want to return a double with only 2 digits after the decimal place. Therefore, you are not formatting you are rounding:
Math.Round(myDouble, 2)
9.98

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.

What's the use case for int32.Parse(String, IFormatProvider) over int32.Parse(String)?

When would it make sense to use int32.Parse(String, IFormatProvider)?
As far as I can tell, this and int32.Parse(String) uses NumberStyles.Integer anyway which only allows a plus, a minus, or digits, optionally surrounded by whitespace, so why does the locale format enter into the equation?
I know about thousand separators, but they don't matter because NumberStyles.Integer disallows them no matter your region.
Consider if you have culture where negative sign is M (minus). I am pretty sure it doesn't exist but just consider that you have something like that. Then you can do:
string str = "M123";
var culture = new CultureInfo("en-US");
culture.NumberFormat.NegativeSign = "M";
int number = Int32.Parse(str, culture);
This would result in -123 as value. This is where you can use int32.Parse(String, IFormatProvider) overload. If you don't specify the culture, then it would use the current culture and would fail for the value M123.
(Old Answer)
It is useful with string with thousand separator
Consider the following example,
string str = "1,234,567";
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE");
int number = Int32.Parse(str, CultureInfo.CurrentCulture);
This would result in an exception since . is the thousand separator in German culture.
For
int number = Int32.Parse("1.234", NumberStyles.AllowThousands);
The above would parse successfully, since the German culture uses . as thousand separator.
But if you have current culture set as US then it would give an exception.
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
int number = Int32.Parse("1.234", NumberStyles.AllowThousands);
See: Int32.Parse Method (String, IFormatProvider)
The provider parameter is an IFormatProvider implementation, such as
a NumberFormatInfo or CultureInfo object. The provider parameter
supplies culture-specific information about the format of s. If
provider is null, the NumberFormatInfo object for the current culture
is used.
Well how about the thousand separators?
I think in USA they use ',' and in Greece they use '.'
USA: 1,000,000
Greece: 1.000.000
In case somebody else is also wondering about this 6 years later, there's still no point in using Int32.ToString(IFormatProvider?) or Int32.Parse(String, IFormatProvider?) since changing the culture makes no difference with the default format and NumberStyles.
You can run this simple test to verify:
using System;
using System.Globalization;
using System.Linq;
class IntToStringTest
{
static void Main()
{
var cultures = CultureInfo.GetCultures(CultureTypes.AllCultures);
var input = -123456789;
var defaultOutput = input.ToString();
var outputCulturePairs = cultures.Select(c => (Output: input.ToString(c), Culture: c));
var parsedOutputs = outputCulturePairs.Select(p => Int32.Parse(p.Output, p.Culture));
Console.WriteLine(outputCulturePairs.All(p => p.Output == defaultOutput));
Console.WriteLine(parsedOutputs.All(o => o == input));
}
}
Edit 8/8/2020: This is only true for .NET Framework. On .NET Core some Arabic cultures use the minus sign AFTER the value.

Parse a Number from Exponential Notation

I need to parse the string "1.2345E-02" (a number expressed in exponential notation) to a decimal data type, but Decimal.Parse("1.2345E-02") simply throws an error
It is a floating point number, you have to tell it that:
decimal d = Decimal.Parse("1.2345E-02", System.Globalization.NumberStyles.Float);
It works if you specify NumberStyles.Float:
decimal x = decimal.Parse("1.2345E-02", NumberStyles.Float);
Console.WriteLine(x); // Prints 0.012345
I'm not entirely sure why this isn't supported by default - the default is to use NumberStyles.Number, which uses the AllowLeadingWhite, AllowTrailingWhite, AllowLeadingSign, AllowTrailingSign, AllowDecimalPoint, and AllowThousands styles. Possibly it's performance-related; specifying an exponent is relatively rare, I suppose.
In addition to specifying the NumberStyles I would recommend that you use the decimal.TryParse function such as:
decimal result;
if( !decimal.TryParse("1.2345E-02", NumberStyles.Any, CultureInfo.InvariantCulture, out result) )
{
// do something in case it fails?
}
As an alternative to NumberStyles.Any you could use a specific set if you're certain of your formats. e.g:
NumberStyles.AllowExponent | NumberStyles.Float
decimal d = Decimal.Parse("1.2345E-02", System.Globalization.NumberStyles.Float);
Be cautious about the selected answer: there is a subtility specifying System.Globalization.NumberStyles.Float in Decimal.Parse which could lead to a System.FormatException because your system might be awaiting a number formated with ',' instead of '.'
For instance, in french notation, "1.2345E-02" is invalid, you have to convert it to "1,2345E-02" first.
In conclusion, use something along the lines of:
Decimal.Parse(valueString.Replace('.',','), System.Globalization.NumberStyles.Float);
The default NumberStyle for decimal.Parse(String) is NumberStyles.Number, so if you just want to add the functionality to allow exponents, then you can do a bitwise OR to include NumberStyles.AllowExponent.
decimal d = decimal
.Parse("1.2345E-02", NumberStyles.Number | NumberStyles.AllowExponent);
I've found that passing in NumberStyles.Float, in some cases, changes the rules by which the string is processed and results in a different output from NumberStyles.Number (the default rules used by decimal.Parse).
For example, the following code will generate a FormatException in my machine:
CultureInfo culture = new CultureInfo("");
culture.NumberFormat.NumberDecimalDigits = 2;
culture.NumberFormat.NumberDecimalSeparator = ".";
culture.NumberFormat.NumberGroupSeparator = ",";
Decimal.Parse("1,234.5", NumberStyles.Float, culture); // FormatException thrown here
I'd recommend using the input NumberStyles.Number | NumberStyles.AllowExponent, as this will allow exponential numbers and will still process the string under the decimal rules.
CultureInfo culture = new CultureInfo("");
culture.NumberFormat.NumberDecimalDigits = 2;
culture.NumberFormat.NumberDecimalSeparator = ".";
culture.NumberFormat.NumberGroupSeparator = ",";
Decimal.Parse("1,234.5",NumberStyles.Number | NumberStyles.AllowExponent, culture); // Does not generate a FormatException
To answer the poster's question, the right answer should instead be:
decimal x = decimal.Parse("1.2345E-02", NumberStyles.Number | NumberStyles.AllowExponent);
Console.WriteLine(x);
Warning about using NumberStyles.Any:
"6.33E+03" converts to 6330 as expected. In German, decimal points are represented by commas, but 6,33E+03 converts to 633000! This is a problem for my customers, as the culture that generates the data is not known and may be different than the culture that is operating on the data. In my case, I always have scientific notation, so I can always replace comma to decimal point before parsing, but if you are working with arbitrary numbers, like pretty-formatted numbers like 1,234,567 then that approach doesn't work.
You don't need to replace the dots (respectively the commas) just specify the input IFormatProvider:
float d = Single.Parse("1.27315", System.Globalization.NumberStyles.Float, new CultureInfo("en-US"));
float d = Single.Parse("1,27315", System.Globalization.NumberStyles.Float, new CultureInfo("de-DE"));
If you want to check and convert the exponent value use this
string val = "1.2345E-02";
double dummy;
bool hasExponential = (val.Contains("E") || val.Contains("e")) && double.TryParse(val, out dummy);
if (hasExponential)
{
decimal d = decimal.Parse(val, NumberStyles.Float);
}
Hope this helps someone.

Decimal Casting

I have a decimal number like this:
62.000,0000000
I need to cast that decimal into int; it will always have zero decimal numbers; so I wont loose any precision. What I want is this:
62.000
Stored on an int variable in c#.
I try many ways but it always give me an error, that the string isn't in the correct format, this is one of the ways i tryied:
int.Parse("62.000,0000000");
Hope you can help me, thanks.
You need to parse it in the right culture. For example, the German culture uses "." as a group separator and "," as the decimal separator - so this code works:
CultureInfo german = new CultureInfo("de-DE");
decimal d = decimal.Parse("62.000,0000000", german);
int i = (int) d;
Console.WriteLine(i); // Prints 62000
Is that what you're after? Note that this will then fail if you present it with a number formatted in a different culture...
EDIT: As Reed mentions in his comment, if your real culture is Spain, then exchange "de-DE" for "es-ES" for good measure.
You need to specify your culture correctly:
var ci = CultureInfo.CreateSpecificCulture("es-ES");
int value = (int) decimal.Parse("60.000,000000", ci);
If you do this, it will correctly convert the number.
Why don't you just cast it to int instead of parsing?

Categories