How to convert string to decimal with 3 decimal places? - c#

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);

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 can I convert string to decimal with trailing zero(s)

Suppose that we have stringvalue=125.32600 when it convert to decimal value with this code
decimal d;
decimal.tryparse(stringvalue,out d)
d value is 125.326
how can I do this convert with final result 125.32600
You cannot because 125.32600 is equal to 125.326. In this case however I guess that you want to print it out with specific format, which can be done like this:
Console.WriteLine(d.ToString("f5"));
Read Standard Numeric Format Strings
UPDATE
Extension method:
public string Format(this decimal source, int precision)
{
if (precision < 0)
{
throw new ArgumentOutOfRangeException("Precision must be a non negative integer");
}
return source.ToString("f" + precision);
}
which can be used like this:
Console.WriteLine(d.Format(5));
Your code works as written (as long as the decimal separator matches your culture):
decimal d;
decimal.TryParse("125.32600", NumberStyles.Number, CultureInfo.InvariantCulture, out d);
s = d.ToString(CultureInfo.InvariantCulture); // 125.32600
Decimal already remembers how many trailing zeros it has. This is caused by decimal representing numbers in non-normalized form, with an integer mantissa and an exponent representing the number of decimal digits. e.g. 125.32600 is represented as 12532600 * 10^-5
The answer is: You can't, at least not like that.
EDIT: correction: decimal already works like that; but you'll still find below a useful way to store your decimals in a DB.
Why? Because that's not how decimals are stored in memory.
Solution: if you need to keep the trailing zeros, just remember the precision explicitly in a separate field (of a class you should create for this purpose); or store the decimals in string form and only convert to decimal as needed.
string strValue = "125.32600";
int precision = strValue.Length - 1; // only the "12332600" part
decimal value = Decimal.Parse(strValue);
stores 8 in precision and 125.326 in value.
To get back the original form:
int afterPt = precision - ((int) value).ToString().Length;
Console.WriteLine(value.ToString("f" + afterPt));
prints
125.32600
P.S. you have to be aware of floating point binary representation issues though, so stuff like 4.05 might be stored as e.g. 4.049999999999999999, so if you need to guarantee this won't happen, use an algorithm that bypasses decimal altogether and uses only integers for storage and computation.
string strValue = "125.32600";
// parse and store
int value = int.Parse(strValue.Replace(".", ""));
int periodIx = strValue.IndexOf(".");
// get back the original representation
string str = value.ToString();
Console.WriteLine(str.Substring(0, periodIx) + "." + str.Substring(periodIx, str.Length - periodIx));
NOTE: Make sure to use , instead of . in locales that need it.
What you can do is count the zeroes in string and then store them in separate DB field. When you want the result with zeroes just concatenate the same no. of zeroes into decimal number string.
ex.
string p="123.456000";
int zeroes=p.Split('0').Length - 1; // guess
decimal value = Decimal.Parse(p); //without zeroes
string valWithZero=value.toString().padRight(zeroes,'0'); //with zeroes
If you really want to have the zeros in the database you could save it as a string, preformatted, but that would be very inefficient.
What is the problem you try to solve by this, there might be a better solution?

Formatting a string number

I want to format a string number. For example:
double number="118176";
It should look like 1181.71 or 1181,71.
I couldn't find any format type. I tried some of format types as ToString("#,0") but it didn't work.
Thanks for any advice.
First of all: a double variable can not take a string. But that aside, something like this should help:
double number = 1181.76;
string output = String.Format("{0:d2}", number);
This takes the number and creates a string from it using the decimal number format with 2 decimal places.
What you didn't say is why you expect the integer 118176 to magically turn into a double with two decimals? The only way would be
double number = 118176;
string output = String.Format("{0:d2}", number / 100.0);
EDIT
Doing what you describe in your comment is a bit more complex:
string priceString = nodeFareList.SelectSingleNode("GenQuoteDetails/TotAmt").InnerText;
double priceDouble = Convert.ToDouble(priceString) / 100.0;
price.InnerHtml += String.Format("{0:c}", priceDouble);
This converts the number in priceDouble to a string with the value formatted like a currency. If you do not want the currency symbol, use the following:
price.InnerHtml += String.Format("{0:d2}", priceDouble);
See Fixed-point on this page (assuming .net): http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx
You'll have to divide by 100 first though.
I think, what you are looking for is this:
String.Format("{0:0,0.0}", 12345.67);
String.Format("{0:0,0}", 12345.67);
See here for details.
Use can refer the below code in case of Java.
1) First define the Decimal Format instance.
DecimalFormat decimalFormat = new DecimalFormat("####.##");
2) Then pass the decimal value to the 'format' method
String dummyString = decimalFormat.format(pressureValue).toString()
where pressureValue - Decimal number
Hope this will be useful.

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