I am working on a calculator and I want to get a thousand dot in my string.
But when i do it like this:
double Answer = 12345;
tbAnswer.Text = Answer.ToString("n");
But when i do it like that it will give me 1,2345.00
I just want the thousand dot and if my double has 3 decimals, that it has 3 decimals, and if it has 2 then 2 etc like:
double Answer = 12345.1; //1,2345.1
double Answer = 12345.23 //1,2345.23
double Answer = 12345.456 //1,2345.456
Is this possible or do i have to stick with the minimum 2 decimals?
There's not a standard format code that will do that - you'll have to use a custom format code:
Answer.ToString("#,###.######");
Note that there's not a format specifier that will provide an unlimited number of decimal places. If you want to support native types up through decimal (which can have 29 decmial places) you could use:
Answer.ToString("#,###.#############################");
But that's ugly, and showing 29 digits of precision is rarely practical.
Related
I'm converting a string to a decimal with decimal.Parse():
decimal.Parse(transactionAmount)
If transactionAmount contains a whole number such as 1, the result is a decimal value of 1. The system I'm sending it to outside of my program treats it as 1 cent for some unknown reason unless it shows up as 1.00. How can I make sure that whole numbers contain a decimal point and a zero such as 1.0?
decimal contains number of digits after the point as part of its internal presentation. So 1m and 1.00m are different `decimal values. As result all parsing/formatting operations will try to preserve that information coming from/to string form unless forced otherwise.
One hack to make sure there are at least two digits after decimal separator is to add proper 0 - 0.00m:
decimal decimalOne = decimal.Parse("1"); // 1.
decimal decimalWithTwoDigit = decimalOne + 0.00m; // 1.00
Note that it is unusual to be sending decimal values in binary form to outside programs. Most likely you actually need to format decimal value with two digits only as covered in Force two decimal places in C# - .ToString("#.00").
Try Convert.ToDecimal() instead of decimal.Parse()
I have encountered something very weird when it comes to the standard numeric format strings in C#. This is probably a known quirk but i can't find anything documenting it and i can't figure out a way to actually get what i want.
I want to take a number like 17.929333333333489 and format it with no decimal places. So i just want "17". But when run this code.
decimal what = 17.929333333333489m;
Console.WriteLine(what.ToString("F0"));
I get this output
18
Looking at Microsoft's documentation on it their examples show the same output.
https://msdn.microsoft.com/en-us/library/kfsatb94(v=vs.110).aspx
// F: -195489100.84
// F0: -195489101
// F1: -195489100.8
// F2: -195489100.84
// F3: -195489100.838
Here is a code example showing the odd issue.
http://csharppad.com/gist/d67ddf5d0535c4fe8e39
This issue is not only limited to the standard ones like "F" and "N" but also the custom ones like "#".
How can i use the standard "F0" formatter and not have it round my number?
From the documentation on Standard Numeric Format Strings:
xx is an optional integer called the precision specifier. The precision specifier ranges from 0 to 99 and affects the number of digits in the result. Note that the precision specifier controls the number of digits in the string representation of a number. It does not round the number itself. To perform a rounding operation, use the Math.Ceiling, Math.Floor, or Math.Round method.
When precision specifier controls the number of fractional digits in the result string, the result strings reflect numbers that are rounded away from zero (that is, using MidpointRounding.AwayFromZero).
So the documentation does indeed discuss this, and there is no apparent way to prevent rounding of the output purely through a format string.
The best I can offer is to truncate the number yourself using Math.Truncate():
decimal what = 17.929333333333489m;
decimal truncatedWhat = Math.Truncate(what);
Console.WriteLine(truncatedWhat.ToString("F0"));
I believe using decimal with "m" at the end rounds up at the given decimal place.
Here is what I experimented.
decimal what = 17.429333333333489m;
Console.WriteLine(what.ToString("F0"));
Console.WriteLine(what.ToString("N0"));
Console.WriteLine(what.ToString("F1"));
Console.WriteLine(what.ToString("N1"))
17
17
17.4
17.4
If you want to get 17, I used different approach using int and deciam
double what = 17.929333333333489;
Console.WriteLine(string.Format("{0:0}", (int)what));
Console.WriteLine(string.Format("{0:0}", what));
Console.WriteLine(string.Format("{0:0.00}", Math.Floor(what*100)/100));
Console.WriteLine(string.Format("{0:0.00}", what));
17
18
17.92
17.93
I am currently formatting a double using the code:
myDouble.ToString("g4");
To get the first 4 decimal places. However I find this often switches over to scientific notation if the number is very large or very small. Is there an easy format string in C# to just have the first four decimal places, or zero if it is too small to be represented in that number of places?
For example, I would like:
1000 => 1000
0.1234567 => 0.1235
123456 => 123456 (Note: Not scientific notation)
0.000001234 => 0 (Note: Not scientific notation)
You can try like this:
0.1234567.ToString("0.####")
Also check Custom Numeric Format Strings
#
Replaces the "#" symbol with the corresponding digit if one is
present; otherwise, no digit appears in the result string.
Also as Jon as correctly pointed that it will round your number. See the note section
Rounding and Fixed-Point Format Strings
For fixed-point format strings
(that is, format strings that do not contain scientific notation
format characters), numbers are rounded to as many decimal places as
there are digit placeholders to the right of the decimal point.
Use the String.Format() method.
String.Format("{0:0.####}", 123.4567123); //output: 123.4567
Note: Num of #'s indicate the maximum number of digits after decimal that are required.
I agree with kjbartel comment.
I wanted exactly what the original question asked. But his question is slightly ambiguous.
The problem with ### format is it fills the slot if a digit can be represented or not.
So it does what the original question asks for some numbers but not others.
My basic need is, and it's a pretty common one, if the number is big I don't need to show decimal places. If the number is small I do want to show decimal places. Basically X number of significant digits.
The "Gn" Format will do significant digits, but it switches to scientific notation if you go over the number of digits. I don't want E notation, ever (same requirement as the question).
So I used fixed format ("Fn") but I calculate the width on the fly based on how "big" the number is.
var myFloatNumber = 123.4567;
var digits = (int) Math.Log10(myFloatNumber);
var maxDecimalplaces = 3;
var format = "F" + Math.Max(0,(maxDecimalplaces - digits));
I swear there was a way to do this in C++ (Visual Studio Flavor) in teh format statement or in C# and perhaps there is, but I can't find it.
So I came up with this. I could have converted to a string and measured length before decimal point as well. But converting it to a string twice felt wrong.
This question already has answers here:
How do I display a decimal value to 2 decimal places?
(19 answers)
Closed 8 years ago.
UPDATE
It's so simple...
When I try to convert the value $ 1.50 from a textbox to a decimal variable, like this:
decimal value = Convert.ToDecimal(textbox1.text.SubString(1));
OR
decimal value = Decimal.Parse(textbox1.text.SubString(1));
I get this result: 1.5.
I know that 1.5 and 1,50 worth the same. But I want to know if it's possible to have two digits after the dot on a decimal variable.
I want to have this as result: 1.50 instead of 1.5 even if these two values worth the same...
I want to have this as result: 1.50 instead of 1.5 even if these two values worth the same..
You have 1.50 or 1.500 or 1.5000. all depending on how you decide to format it / print it.
Your decimal value is stored in floating point format. How many decimal points you see is about output, not storage (at least until you reach the limit of the precision of the particular binary format, and 2 decimal places is nowhere close). A C# Decimal stores up to 29 significant digits.
See this reference. It gives an example of a currency format. It prints something like:
My amount = $1.50
But, you aren't storing a $ sign..., so where does it come from? The same place the "1.50" comes from, it is in your format specifier.
http://msdn.microsoft.com/en-us/library/364x0z75.aspx
Console.WriteLine("My amount = {0:C}", x);
var s = String.Format("My amount = {0:C}", x);
It is no different than saying, how do I store 1/3 (a repeating decimal)?
Well, it isn't 0.33, but if I only look at the first 2 digits, then it is 0.33. The closer i look (the more decimal places I ask for in the format), the more I get.
0.33333333333333... but that doesn't equal 0.330
You're confusing storage of the numeric value with rendering it as a string (display).
decimal a=1.5;
decimal b=1.50;
decimal c=1.500;
In memory: the zeros are kept to keep track of how much precision is desired. See the link in the comment by Chris Dunaway below.
However, note these tests:
(a==b) = true
(b==c)=true
Parsing ignores the trailing zeros, so your example one creates them, then they're ignored, as they're mathmatically irrelevant.
Now how you convert to string is a different story:
a.ToString("N4") returns the string "1.5000" (b. and c. the same)
a.ToString("N2") returns the string "1.50"
As the link in the comment explains, if you just to a.ToString, trailing zeros are retained.
If you store it in a database column as type 'decimal', it might be a different story - I haven't researched the results. These are the rules that .Net uses and while the databases might use different rules, these behaviours often follow official standards, so if you do your research you might find that the database behaves the same way!
The important thing to remember is that there is a difference between the way numbers are stored in memory and the way they are represented as strings. Floating point numbers may not retain trailing zeros this way, it's up to the rules of the in-memory storage of the type (usually set by standards bodies in very specific, detailed ways).
I have a number with a variable number of digits after the decimal point. I want to format the number with commas and all decimal numbers.
For example: 42,023,212.0092343234
If I use ToString("N") I get only 2 decimals, ToString("f") gives me all decimals no commas. How do I get both?
Not sure (and unable to test right now) but would something like this work?
"#,##0.################"
string.Format("{0:#,##0.############}", value);
will give you up to 12 decimal places.
There is not a custom format specifier for "all following digits", so something like this will be closest to what you want.
Note too that you're limited by the precision of your variable. A double only has 15-16 digits of precision, so as your left-hand side gets bigger the number of decimal places will fall off.
UPDATE: Looking at the MSDN documentation on the System.Double type, I see this:
By default, a Double value contains 15
decimal digits of precision, although
a maximum of 17 digits is maintained
internally.
So I think pdr's on to something, actually. Just do this:
// As long as you've got at least 15 #s after the decimal point,
// you should be good.
value.ToString("#,#.###############");
Here's an idea:
static string Format(double value)
{
double wholePart = Math.Truncate(value);
double decimalPart = Math.Abs(value - wholePart);
return wholePart.ToString("N0") + decimalPart.ToString().TrimStart('0');
}
Example:
Console.WriteLine(Format(42023212.0092343234));
Output:
42,023,212.00923432409763336
Ha, well, as you can see, this gives imperfect results, due (I think) to floating point math issues. Oh well; it's an option, anyway.
Try ToString("N2")
Let's try this
[DisplayFormat(DataFormatString = "{0:0,0.00}")]
Here is the way somewhat to reach to your expectation...
decimal d = 42023212.0092343234M;
NumberFormatInfo nfi = (NumberFormatInfo) CultureInfo.InvariantCulture.NumberFormat.Clone();
nfi.NumberDecimalDigits= (d - Decimal.Truncate(d)).ToString().Length-2;
Console.WriteLine(d.ToString("N",nfi));
For more detail about NumberFormatInfo.. look at MSDN ..
http://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.aspx