double.Parse doesn't work with some country apparently - c#

Basically, I have this really simple calculation:
int bTaxPrice = int.Parse(prices[wep]);
double t = double.Parse("1." + taxes);
double price = Math.Round(t * bTaxPrice);
I'll give you an example for how the calculation should work, lets say t=1.1 and bTaxPrice=1279, then 1.1*1279 = 1406.9, but since I'm rounding the result the price equals 1407.
For some users from another country (Denmark) that are using my C# Winforms program are experiencing a problem that causes the number not to round, but to add the last 2 digits after the decimal point.
Our result for the calculation above was 1407, for them it's 140690.
I read about it in the internet, and some countries have something special with there decimal point.
What is a good fix for this kind of issue?

Actually, many countries use a comma for their decimal separator.
If you want to use the dot as a separator, use the invariant CultureInfo:
double.Parse("1." + taxes, CultureInfo.InvariantCulture);

Some countries use a comma as decimal separator. You could fix this by supplying CultureInfo.InvariantCulture to the double.Parse method.

Related

How would I format a second timer? [duplicate]

I am currently building a sales module for a clients website. So far I have got the sale price to calculate perfectly but where I have come stuck is formatting the output to 2 decimal places.
I am currently calling this in a variable so that I can data bind the results to a listview.
Sale = float.Parse(((x.Sale_Price - (x.Sale_Price * (x.Discount_Price / 100))).ToString())),
Can anyone show me how to format the output to 2 decimal places?? Many Thanks!
You can pass the format in to the ToString method, e.g.:
myFloatVariable.ToString("0.00"); //2dp Number
myFloatVariable.ToString("n2"); // 2dp Number
myFloatVariable.ToString("c2"); // 2dp currency
Standard Number Format Strings
The first thing you need to do is use the decimal type instead of float for the prices. Using float is absolutely unacceptable for that because it cannot accurately represent most decimal fractions.
Once you have done that, Decimal.Round() can be used to round to 2 places.
This is for cases that you want to use interpolated strings. I'm actually posting this because I'm tired of trial and error and eventually scrolling through tons of docs every time I need to format some scalar.
$"{1234.5678:0.00}" "1234.57" 2 decimal places, notice that value is rounded
$"{1234.5678,10:0.00}" " 1234.57" right-aligned
$"{1234.5678,-10:0.00}" "1234.57 " left-aligned
$"{1234.5678:0.#####}" "1234.5678" 5 optional digits after the decimal point
$"{1234.5678:0.00000}" "1234.56780" 5 forced digits AFTER the decimal point, notice the trailing zero
$"{1234.5678:00000.00}" "01234.57" 5 forced digits BEFORE the decimal point, notice the leading zero
$"{1234.5612:0}" "1235" as integer, notice that value is rounded
$"{1234.5678:F2}" "1234.57" standard fixed-point
$"{1234.5678:F5}" "1234.56780" 5 digits after the decimal point, notice the trailing zero
$"{1234.5678:g2}" "1.2e+03" standard general with 2 meaningful digits, notice "e"
$"{1234.5678:G2}" "1.2E+03" standard general with 2 meaningful digits, notice "E"
$"{1234.5678:G3}" "1.23E+03" standard general with 3 meaningful digits
$"{1234.5678:G5}" "1234.6" standard general with 5 meaningful digits
$"{1234.5678:e2}" "1.23e+003" standard exponential with 2 digits after the decimal point, notice "e"
$"{1234.5678:E3}" "1.235E+003" standard exponential with 3 digits after the decimal point, notice "E"
$"{1234.5678:N2}" "1,234.57" standard numeric, notice the comma
$"{1234.5678:C2}" "$1,234.57" standard currency, notice the dollar sign
$"{1234.5678:P2}" "123,456.78 %" standard percent, notice that value is multiplied by 100
$"{1234.5678:2}" "2" :)
Performance Warning
Interpolated strings are slow. In my experience this is the order (fast to slow):
value.ToString(format)+" blah blah"
string.Format("{0:format} blah blah", value)
$"{value:format} blah blah"
String.Format("{0:#,###.##}", value)
A more complex example from String Formatting in C#:
String.Format("{0:$#,##0.00;($#,##0.00);Zero}", value);
This will output “$1,240.00″ if passed 1243.50. It will output the same format but in parentheses if the number is negative, and will output the string “Zero” if the number is zero.
I believe:
String.Format("{0:0.00}",Sale);
Should do it.
See Link
String Format Examples C#
As already mentioned, you will need to use a formatted result; which is all done through the Write(), WriteLine(), Format(), and ToString() methods.
What has not been mentioned is the Fixed-point Format which allows for a specified number of decimal places. It uses an 'F' and the number following the 'F' is the number of decimal places outputted, as shown in the examples.
Console.WriteLine("{0:F2}", 12); // 12.00 - two decimal places
Console.WriteLine("{0:F0}", 12.3); // 12 - ommiting fractions
string outString= number.ToString("####0.00");
I like to use
$"{value:0.##}
It displays two decimals only if there is some value at those places.
Examples:
$"{50.255:0.##} //50,25
$"{50.2:0.##} //50,2
$"{50.00:0.##} //50
private float LimitDecimalPlace(double number,int limitPlace)
{
float result = 0;
string sNumber = number.ToString();
int decimalIndex = sNumber.IndexOf(".");
if (decimalIndex != -1)
{
sNumber = sNumber.Remove(decimalIndex + limitPlace + 1);
}
result = float.Parse(sNumber);
return result;
}

How to return a double whole number with 2 zeros after the dot? [duplicate]

decimal Debitvalue = 1156.547m;
decimal DEBITAMT = Convert.ToDecimal(string.Format("{0:0.00}", Debitvalue));
I have to get only two decimal places but by using this code I am getting 1156.547.
Which format do I have to use to display two decimal places?
Your question is asking to display two decimal places. Using the following String.format will help:
String.Format("{0:.##}", Debitvalue)
this will display then number with up to two decimal places(e.g. 2.10 would be shown as 2.1 ).
Use "{0:.00}", if you want always show two decimal places(e.g. 2.10 would be shown as 2.10 )
Or if you want the currency symbol displayed use the following:
String.Format("{0:C}", Debitvalue)
Use Math.Round() for rounding to two decimal places
decimal DEBITAMT = Math.Round(1156.547m, 2);
If you want to round the decimal, look at Math.Round()
The best approach if you want to ALWAYS show two decimal places (even if your number only has one decimal place) is to use
yournumber.ToString("0.00");
I use
decimal Debitvalue = 1156.547m;
decimal DEBITAMT = Convert.ToDecimal(string.Format("{0:F2}", Debitvalue));
here is another approach
decimal decimalRounded = Decimal.Parse(Debitvalue.ToString("0.00"));
For only to display, property of String can be used as following..
double value = 123.456789;
String.Format("{0:0.00}", value);
Using System.Math.Round. This value can be assigned to others or manipulated as required..
double value = 123.456789;
System.Math.Round(value, 2);
Another way :
decimal.Round(decimalvalue, 2, MidpointRounding.AwayFromZero);
Probably a variant of the other examples, but I use this method to also make sure a dot is shown before the decimal places and not a comma:
someValue.ToString("0.00", CultureInfo.InvariantCulture)
Another option is to use the Decimal.Round Method
If someone looking for a way to display decimal places even if it ends with ".00", use this:
String.Format("{0:n1}", value)
Reference:
https://learn.microsoft.com/pt-br/dotnet/standard/base-types/standard-numeric-format-strings#the-numeric-n-format-specifier
To display two decimal digits, try the given syntax.
string.Format("{0:0.00}", Debitvalue)
In some tests here, it worked perfectly this way:
Decimal.Round(value, 2);
Hope this helps

display both dollar sign and two decimals

i haved looked all over the place! I swear! im trying to get my output to display both the "$" and two decimals to the right of the period. Im using C#
//declare variable
decimal decInputDays;
decimal decInputAmountofBooks;
decimal decOutputAmountofFine;
decimal FINE_CALCULATE = .05m;
//get values from the form
decInputDays = decimal.Parse(txtDays.Text);
decInputAmountofBooks = decimal.Parse(txtBooks.Text);
//determine fine amount
decOutputAmountofFine = decInputDays * decInputAmountofBooks * FINE_CALCULATE;
//display fine amount
lblAmount.Text = decOutputAmountofFine.ToString("c");
You need
decimalVal.ToString("C2")
The exact output format will depend on the current Culture selection on the computer it's being run on, but ToString("C") should produce output with currency symbol, thousands separators where required, plus two decimals following. You can specify a number if you need more or fewer decimal digits, but the default of 2 digits is the most common.
If all else fails you should be able to force the format like this:
lblAmount.Text = string.Format("${0:#,0.00}", decOutputAmountofFine);
Or if you're using C# version 6 (VS2015):
lblAmount.Text = $"${decOutputAmountofFine:#,0.00}";
Note that #, is the "insert thousands separator" specifier and can still be affected by localization... but I don't know of any locales that use any value other than 3 for separator distance (System.Globalization.NumberFormatInfo.CurrencyGroupSizes). Check the values in System.Globalization.CultureInfo.CurrentCulture.NumberFormat to see what is configured for your location.
You didn't specify what your current result is. But whatever it is, it sounds like your problem is culture-related.
Consider forcing the culture to en-US. It should give you the currency format you are looking for:
decOutputAmountofFine.ToString("c", CultureInfo.GetCultureInfo("en-US"));

How to format double value as price without currency sign and with special case for no decimals

I want to string format a double value - a product price - with two decimals when the price is eg. 12.99, and with a ",-" when the price is 12.00. Is that possible using the ToString() extension in C# .NET?
I have tried
price.ToString(#"#,0.00;-#,0.00;0\,-");
and this gives me "12.99" just fine. But 12.00 shows as "12.00", and I would prefer it to be "12,-". I use groups in the above statement to separate positive, negative and zero numbers.
Can this be done without doing if/else logic in the code?
Cheers
Jens
price.ToString(#"#,0.00;-#,0.00;0\,-").Replace(".00", ",-");

Converting String To Float in C#

I am converting a string like "41.00027357629127", and I am using;
Convert.ToSingle("41.00027357629127");
or
float.Parse("41.00027357629127");
These methods return 4.10002732E+15.
When I convert to float I want "41.00027357629127". This string should be the same...
Your thread's locale is set to one in which the decimal mark is "," instead of ".".
Try using this:
float.Parse("41.00027357629127", CultureInfo.InvariantCulture.NumberFormat);
Note, however, that a float cannot hold that many digits of precision. You would have to use double or Decimal to do so.
You can use the following:
float asd = (float) Convert.ToDouble("41.00027357629127");
First, it is just a presentation of the float number you see in the debugger. The real value is approximately exact (as much as it's possible).
Note: Use always CultureInfo information when dealing with floating point numbers versus strings.
float.Parse("41.00027357629127",
System.Globalization.CultureInfo.InvariantCulture);
This is just an example; choose an appropriate culture for your case.
Use Convert.ToDouble("41.00027357629127");
Convert.ToDouble documentation
The precision of float is 7 digits. If you want to keep the whole lot, you need to use the double type that keeps 15-16 digits. Regarding formatting, look at a post about formatting doubles. And you need to worry about decimal separators in C#.
A 2022 way of converting an string that represents a float value:
(float)Convert.ToDecimal(value, CultureInfo.GetCultureInfo("en-US"));
where you also can choose what kind of float are you expecting to convert, because some CultureInfo instances represents decimal values with a , and others with ..
If you need more decimals to obtain more precision, just not use float
Convert.ToDecimal(value, CultureInfo.GetCultureInfo("en-US"));
You can double.Parse("41.00027357629127");
First you need to using System.Globalization to dealing convertions from string to float/double/decimal without problem.
Then you can call Parse on float(or double/decimal depending at the accuracy you need), and as argument in Parse you need your string (you can store it in a variable if you want) and CultureInfo.InvariantCulture.NumberFormat
So, as previous users already explained:
float.Parse("41.00027357629127", CultureInfo.InvariantCulture.NumberFormat);
You can use parsing with double instead of float to get more precision value.

Categories

Resources