Formatting decimal numbers in C# - 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.

Related

How to convert string to decimal with 3 decimal places?

string num = 23.6;
I want to know how can I convert it into decimal with 3 decimal places
like
decimal nn = 23.600
Is there any method?
I try my best..
First of all your string num = 23.6; won't even compile. You need to use double quotes with your strings like string num = "23.6";
If you wanna get this as a decimal, you need to parse it first with a IFormatProvider that have . as a NumberDecimalSeparator like InvariantCulture(if your CurrentCulture uses . already, you don't have to pass second paramter);
decimal nn = decimal.Parse(num, CultureInfo.InvariantCulture);
Now we have a 23.6 as a decimal value. But as a value, 23.6, 23.60, 23.600 and 23.60000000000 are totally same, right? No matter which one you parse it to decimal, you will get the same value as a 23.6M in debugger. Looks like these are not true. See Jon Skeet comments on this answer and his "Keeping zeroes" section on Decimal floating point in .NET article.
Now what? Yes, we need to get it's textual representation as 23.600. Since we need only decimal separator in a textual representation, The "F" Format Specifier will fits out needs.
string str = nn.ToString("F3", CultureInfo.InvariantCulture); // 23.600
There are two different concepts here.
Value
View
you can have a value of 1 and view it like 1.0 or 1.0000 or +000001.00.
you have string 23.6. you can convert it to decimal using var d = decimal.Parse("23.6")
now you have a value equals to 23.6 you can view it like 23.600 by using d.ToString("F3")
you can read more about formatting decimal values
the thing that works for me in my case is num.ToString("#######.###")
A decimal is not a string, it does not display the trailing zeros. If you want a string that displays your 3 decimal places including trailing zeros, you can use string.Format:
decimal nn= 23.5;
var formattedNumber = string.Format("{0,000}", nn);

How to change display format of long variable?

I have a variable of type Long i.e.
long quantity=1000;
I want to display it like 1,000 in Grid (Must need commas)
How do i achieve this?
I am using a Telerik Grid and I am binding the data as follows:
columns.Bound(tempProductList => tempProductList.tempProductListQuantity) .Title("Quantity")
Here you have a list of all the standard numeric formats. I think "N" is the one you want.
long l = 1234;
string s = l.ToString("N0"); //gives "1,234"
The "0" after the format specifier is the number of desired decimal places (usually 2 by default).
Note that this version is culture-sensitive, i.e., in my country, we use dots (".") as thousand separators, so the actual returned value will be "1.234" instead of the "1,234". If this is desired behaviour, just leave it as is, but if you need to use commas always, then you should specify a culture as a parameter to the ToString method, like
l.ToString("N0", CultureInfo.InvariantCulture); //always return "1,234"
You could create a Custom Culture that will allow you to specify the thousand separator.
From this article:
//Create first the format provider the String.Format
//will use to format our string
CultureInfo cultureToUse = new CultureInfo("fi-FI");
Console.WriteLine("Using the following CultureInfor " +
cultureToUse.Name);
//Now practice some decimal numbers
//Here we override the culture specific formattings
cultureToUse.NumberFormat.CurrencyDecimalDigits = 3;
cultureToUse.NumberFormat.NumberDecimalDigits = 3;
cultureToUse.NumberFormat.NumberGroupSeparator = " ";
cultureToUse.NumberFormat.CurrencySymbol = "euro";
cultureToUse.NumberFormat.NumberDecimalSeparator = ",";
Next you would need to use this culture when formatting the numbers.
You could do the formattin gby hand but you could also assign the culture to the Current(UI)Culture property of the current thread.
If you want to consider the international point of view, there will not be always commas before the decimal part. ToString function will give you what you want.
(1000.0).ToString("N",new CultureInfo("en-US")) = 1,000.00
(1000.0).ToString("N",new CultureInfo("is-IS")) = 1.000,00

Converting string to currency and globalization issue

I have this:
var pl = new CultureInfo("pl-PL");
decimal valsue = decimal.Parse("2,25 PLN", pl);
It works ok if i don't put "PLN" into my string. But PLN is currency in my country and i think that it should parse, so maybe i am doing something wrong? Is there any option to parse this into decimal with "PLN" attached to the string?
If you take a look at your CultureInfo's NumberFormat object, this will yield some clues about how it intends to parse values. In particular, NumberFormat.CurrencySymbol for the "pl-PL" culture is zł.
In other words, this expression would parse successfully: decimal.Parse("2,25 zł", pl);
If you prefer to use PLN as the currency symbol (technically, it's the currency code), it is possible to configure a custom NumberFormat, like so:
var pln = (NumberFormatInfo) pl.NumberFormat.Clone(); // Clone is needed to create a copy whose properties can be set.
pln.CurrencySymbol = "PLN";
decimal valsue = decimal.Parse("2,25 PLN", NumberStyles.Currency, pln);
But note the usage of NumberStyles.Currency in the Parse call: by default, decimal.Parse accepts only strings containing numeric values, without currency formatting.

Changing the number of integers on a output value after the decimal point

So I'm learning and practicing WP7 application development.
I'm working with integers (currency), and it seems to always display four integers after the decimal place. I'm trying to cut it down to just either ONE or TWO decimal places.
I've been trying to use the "my variable.ToString("C2")" (C for Currency, 2 for number of ints after the decimal)
I'm probably missing something obvious, but please help
decimal number = new decimal(1000.12345678);
string text = number.ToString("#.##");
Output:
1000,12
An other way:
NumberFormatInfo nfi = new NumberFormatInfo();
nfi.CurrencyDecimalDigits = 2;
decimal val = new decimal(1000.12345678);
string text = val.ToString("c", nfi);
When formatting a currency, NumberFormatInfo allows specifying following properties as well:
CurrencyDecimalDigits
CurrencyDecimalSeparator
CurrencyGroupSeparator
CurrencyGroupSizes
CurrencyNegativePattern
CurrencyPositivePattern
CurrencySymbol
See Custom Numeric Format Strings on MSDN for more examples
The "C" format string defines the currency specifier as described on MSDN. This will include the currency symbol for the current culture, or for a specific culture if supplied, e.g.
double amount = 1234.5678;
string formatted = amount.ToString("C", CultureInfo.CreateSpecificCulture("en-US"));
// This gives $1234.56
In your case, it seems that you have a limited set of currency symbols that you support, so I would suggest using the fixed point format specifier "F" instead. By default this will give you 2 decimal points, but you can specify a number to vary this, e.g.
double amount = 1234.5678;
string formatted = amount.ToString("F");
// This gives 1234.56
formatted = amount.ToString("F3");
// This gives 1234.567
Using the fixed point specifier will give you control over the number of decimal points and enable you to concatenate the currency symbol.
The only thing I would add to "sll" answer is to pay attention on Culture (they often forget to mantion this), like this (example)
string text = val.ToString("#.##", CultureInfo.InvariantCulture);
double total = 526.4134
string moneyValue = total.ToString("c");
This will display it in this format: $#.##

Convert string to decimal with format

I need convert a String to a decimal in C#, but this string have different formats.
For example:
"50085"
"500,85"
"500.85"
This should be convert for 500,85 in decimal. Is there is a simplified form to do this convertion using format?
Some cultures use a comma to indicate the floating point. You can test this with the following code on an aspx page:
var x = decimal.Parse("500,85");
Response.Write(x + (decimal)0.15);
This gives the answer 501 when the thread culture has been set to a culture that uses the comma as floating point. You can force this like so:
var x = decimal.Parse("500,85", new NumberFormatInfo() { NumberDecimalSeparator = "," });
While decimal.Parse() is the method you are looking for, you will have to provide a bit more information to it. It will not automatically pick between the 3 formats you give, you will have to tell it which format you are expecting (in the form of an IFormatProvider). Note that even with an IFormatProvider, I don't think "50085" will be properly pulled in.
The only consistent thing I see is that it appears from your examples that you always expect two decimal places of precision. If that is the case, you could strip out all periods and commas and then divide by 100.
Maybe something like:
public decimal? CustomParse(string incomingValue)
{
decimal val;
if (!decimal.TryParse(incomingValue.Replace(",", "").Replace(".", ""), NumberStyles.Number, CultureInfo.InvariantCulture, out val))
return null;
return val / 100;
}
This will work, depending on your culture settings:
string s = "500.85";
decimal d = decimal.Parse(s);
If your culture does not by default allow , instead of . as a decimal point, you will probably need to:
s = s.Replace(',','.');
But will need to check for multiple .'s... this seems to boil down to more of an issue of input sanitization. If you are able to validate and sanitize the input to all conform to a set of rules, the conversion to decimal will be a lot easier.
Try this code below:
string numValue = "500,85";
System.Globalization.CultureInfo culInfo = new System.Globalization.CultureInfo("fr-FR");
decimal decValue;
bool decValid = decimal.TryParse(numValue, System.Globalization.NumberStyles.Number, culInfo.NumberFormat, out decValue);
if (decValid)
{
lblDecNum.Text = Convert.ToString(decValue, culInfo.NumberFormat);
}
Since I am giving a value of 500,85 I will assume that the culture is French and hence the decimal separator is ",". Then decimal.TryParse(numValue, System.Globalization.NumberStyles.Number, culInfo.NumberFormat,out decValue);
will return the value as 500.85 in decValue. Similarly if the user is English US then change the culInfo constructor.
There are numerous ways:
System.Convert.ToDecimal("232.23")
Double.Parse("232.23")
double test;
Double.TryParse("232.23", out test)
Make sure you try and catch...
This is a new feature called Digit Grouping Symbol.
Steps:
Open Region and Language in control panel
Click on Additional setting
On Numbers tab
Set Digit Grouping Symbol as custom setting.
Change comma; replace with (any character as A to Z or {/,}).
Digit Grouping Symbol=e;
Example:
string checkFormate = "123e123";
decimal outPut = 0.0M;
decimal.TryParse(checkFormate, out outPut);
Ans: outPut=123123;
Try This
public decimal AutoParse(string value)
{
if (Convert.ToDecimal("3.3") == ((decimal)3.3))
{
return Convert.ToDecimal(value.Replace(",", "."));
}
else
{
return Convert.ToDecimal(value.Replace(".", ","));
}
}

Categories

Resources