I have a string like this: "000123".
I want to know how to convert this string to decimal but keep the leading zeros. I have used Convert.ToDecimal(), Decimal.TryParse & Decimal.Parse. But all of those methods keep removing the leading zeros. They give me an output: 123. I want the decimal returning 000123. Is that possible ?
No, it's not. System.Decimal maintains trailing zeroes (since .NET 1.1) but not leading zeroes. So this works:
decimal d1 = 1.00m;
Console.WriteLine(d1); // 1.00
decimal d2 = 1.000m;
Console.WriteLine(d2); // 1.000
... but your leading zeroes version won't.
If you're actually just trying to format with "at least 6 digits before the decimal point" though, that's easier:
string text = d.ToString("000000.#");
(That will lose information about the number of trailing zeroes, mind you - I'm not sure how to do both easily.)
So you need to store 000123 in a decimal variable, First of all it is not possible since 000123 is not a Real Number. we can store only Real numbers within the range from -79,228,162,514,264,337,593,543,950,335 to +79,228,162,514,264,337,593,543,950,335 in a decimal variable. No worries you can achieve the target, decimal.Parse() to get the value(123) from the input(as you already did) and process the calculations with that value. and use .ToString("000000") whenever you wanted to display it as 000123
Related
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;
}
I'm very new to c# programming. I want to know how to add leading zeros for a integer type in c#.
ex:
int value = 23;
I want to use it like this ;
0023
Thanks in advance
You can't. There's no such contextual information in an int. An integer is just an integer.
If you're talking about formatting, you could use something like:
string formatted = value.ToString("0000");
... that will ensure there are at least 4 digits. (A format string of "D4" will have the same effect.) But you need to be very clear in your mind that this is only relevant in the string representation... it's not part of the integer value represented by value. Similarly, value has no notion of whether it's in decimal or hex - again, that's a property of how you format it.
(It's really important to understand this in reasonably simple cases like this, as it tends to make a lot more difference for things like date/time values, which again don't store any formatting information, and people often get confused.)
Note that there's one type which may surprise you: decimal. While it doesn't consider leading zeroes, it does have a notion of trailing zeroes (implicitly in the way it's stored), so 1.0m and 1.00m are distinguishable values.
Basically you want to add padding zeros.
string format specifier has a very simple method to this.
string valueAfterpadding;
int value = 23;
valueAfterpadding = value.ToString("D4");
Console.WriteLine(valueAfterpadding );
this solve your problem. just google it.
Integer wont accept leading zeros, it will only hold the real value of the integer.
The best we to have leading zeros is to convert it to string.
If you need a 4 digit value always, use the .ToString formatting to add leading 0's.
int value = 23;
var result = value.ToString("0000");
or if you want to have a leading 00 to any number, better append 00 to the string equivalent of the integer.
int value = 23;
var result = "00" + value.ToString();
This is not a programming issue. Numbers have no leading zeroes.
There are two things here that you can do:
If it is a number, then format it on the way out.
If it is something like a code (article number etc.) - those are NOT NUMBERS.
The second point is important. Things like social security numbers, part numbers etc. are strings - with only numeric characters allowed. You never add or subtract them and you must be prepared for format changes. They are not integers or any other number form to start with.
Consider the following code:
decimal decimalVal = 4.00M;
double doubleVal = 5.00;
Console.Write(decimalVal);
Console.Write(doubleVal);
Why are the zeroes after the decimal in decimalVal displayed, but those after the decimal in doubleVal are not?
The difference you're seeing is due to how Console.Write() was designed.
When you call Console.Write like this:
Console.Write(decimalVal);
Console.Write(doubleVal);
Under the covers, it's actually calling ToString() and passing it your current culture, equivalent to this:
Console.Write(decimalVal.ToString(Thread.CurrentThread.CurrentCulture));
Console.Write(doubleVal.ToString(Thread.CurrentThread.CurrentCulture));
Those two lines do not specify a format, so the general ("G") format for your culture is used, as noted in the documentation for Double.ToString() and Decimal.ToString().
Console.Write(decimalVal.ToString("G"));
Console.Write(doubleVal.ToString("G"));
So what does the "G" format specifier output? Again, from the docs:
The result contains a decimal point if required, and trailing zeros after the decimal point are omitted. If the precision specifier is present and the number of significant digits in the result exceeds the specified precision, the excess trailing digits are removed by rounding.
However, if the number is a Decimal and the precision specifier is omitted ... trailing zeros are preserved.
(my emphasis added)
So the end result is that Console.Write() outputs...
Your double value without trailing zeroes.
Your decimal value with trailing zeroes.
At first, I chalked the difference up to "developer's choice", but then Raymond Chen and Jeff Mercado both commented on the underlying reason:
It's because decimal remembers how much precision it has. 4.00M and 4.0M are not the same. (Although they compare equal.) Conversion to string reveals the precision. Double does not track precision. ~Raymond
decimal must preserve the precision of the value it represents. double doesn't. When you define a decimal ``4 with 3 significant figures, that is exactly what you get. The double 5.00 can be represented with the exact value 5. How many decimal places it had is not encoded into the value. ~Jeff
Additionally, from the Decimal documentation:
The scaling factor also preserves any trailing zeros in a Decimal number. Trailing zeros do not affect the value of a Decimal number in arithmetic or comparison operations. However, trailing zeros might be revealed by the ToString method if an appropriate format string is applied.
(The "scale factor" is a value that represents the fractional portion of the decimal - the portion after the decimal point.)
What this means is, although 3.0m, 3.00m and 3.000000m are all considered equal when you compare them, the Decimal type stores an appropriate scale factor to ensure the trailing zeroes are not lost.
This does not apply to the Double type, where leading zeroes are not retained. Although, if you had a double and wanted to ensure at least a couple zeroes were displayed, you could specify a format:
Console.Write(doubleVal.ToString("F2")); // outputs 5.00
I’m getting numbers from a database. Some are stored as double in the database and some are stored as string.
What I want to do is count the decimal number of caracters so : 345.34938 would give me a result of 5.
As I said, some of my double come from the database as double and some as string. I’m wondering if there could be any kind of problem when casting the string numbers to double, hence giving me wrong result when trying to count the decimals.
I think I should be ok but I’m afraid that in some situations I’ll end up receiving wrong double numbers when they’re casted from the string (thinking about having 1.9999999 instead of 2.0, things like that)...
Is there any kind of risk that casting my number from string to double would give me strange result when stored as double in my application ? Am I being to frisky around that ?
Consider converting the string representations to System.Decimal with the decimal.Parse method. Because for a decimal there's a much better correspondence between the value of the number and its string representation. Also, it can handle more digits.
A System.Decimal will preserve trailing zeros present in the string (like "2.7500"), which a System.Double will not.
But if your strings never have more than 15 digits in total (including digits before the decimal point .), your approach with double will probably work. But the exact number represented almost always differs from "what you see" with a double, so the number of decimal figures is to be understood as what double.ToString() shows...
Maybe it's easier to just use the string directly, like
int numberOfDecimals = myString.Length - (myString.IndexOf('.') + 1);
Is there a reason that a C# System.Decimal remembers the number of trailing zeros it was entered with?
See the following example:
public void DoSomething()
{
decimal dec1 = 0.5M;
decimal dec2 = 0.50M;
Console.WriteLine(dec1); //Output: 0.5
Console.WriteLine(dec2); //Output: 0.50
Console.WriteLine(dec1 == dec2); //Output: True
}
The decimals are classed as equal, yet dec2 remembers that it was entered with an additional zero. What is the reason/purpose for this?
It can be useful to represent a number including its accuracy - so 0.5m could be used to mean "anything between 0.45m and 0.55m" (with appropriate limits) and 0.50m could be used to mean "anything between 0.495m and 0.545m".
I suspect that most developers don't actually use this functionality, but I can see how it could be useful sometimes.
I believe this ability first arrived in .NET 1.1, btw - I think decimals in 1.0 were always effectively normalized.
I think it was done to provide a better internal representation for numeric values retrieved from databases. Dbase engines have a long history of storing numbers in a decimal format (avoiding rounding errors) with an explicit specification for the number of digits in the value.
Compare the SQL Server decimal and numeric column types for example.
Decimals represent fixed-precision decimal values. The literal value 0.50M has the 2 decimal place precision embedded, and so the decimal variable created remembers that it is a 2 decimal place value. Behaviour is entirely by design.
The comparison of the values is an exact numerical equality check on the values, so here, trailing zeroes do not affect the outcome.