Difference between ToString("N2") and ToString("0.00") - c#

What is the difference between ToString("N2") and ToString("0.00")?

From Standard Numeric Format Strings
The number is converted to a string of
the form "-d,ddd,ddd.ddd…", where '-'
indicates a negative number symbol if
required, 'd' indicates a digit (0-9),
',' indicates a thousand separator
between number groups, and '.'
indicates a decimal point symbol.
It would seem that N will include thousands separators, whereas 0.00 will not.
See also Custom Numeric Format Strings

It's all about the decimal places
N2 will work the same way for 500.00, but when you have 5000.00, N2 will display as
5,000.00
instead of
5000.00
See Standard Numeric Format Strings for more information.

Basically, ToString("N2") will use the CultureInfo to format the number. This means that your thousands separator might be different depending on the used CultureInfo. You can also pass the desired CultureInfo if you want.

Both give you two decimal places, but you can see the difference easily if you check larger numbers:
var d = 1234567.89;
for (var i = 0; i < 10; ++i) {
Console.WriteLine(d.ToString("N2") + "\t" + d.ToString("0.00"));
d /= 10.0;
}
outputs
1.234.567,89 1234567,89
123.456,79 123456,79
12.345,68 12345,68
1.234,57 1234,57
123,46 123,46
12,35 12,35
1,23 1,23
0,12 0,12
0,01 0,01
0,00 0,00
Execute code online at dotnetfiddle.net

The thousand separator is an issue. Using "n2" will give you 3,543 where using "0.00" will give you 3543. The comma can break down-stream code that might have to parse that value back to a decimal, especially client-side js.

Here is example to explain
int rupees=567.3423;
string rp=rupees.tostring("N2");
--Answer is rp="567.34";
-- N2 gives upto two decimal records.

Related

How do i print out the decimal part of a number to a certain number of digits in C Sharp C#

Can someone help me out ?
How do I print out the decimals of a number to a certain number of decimals in C# or should i say, how do you add trailing zeros to meet the specified number.
Example: printing to 7 decimals
5.66 should return 0.6600000
0.123456 should return 0.1234560
A simple way to specify the number of digits is to use a custom formatting string. '0' is a placeholder for a digit to always print, '#' would be an digit to print if relevant. So 7 decimals would be "0.0000000", There are also standard formatting strings that may be useful.
If you are not interested in the whole number part you can just subtract it:
var decimalPart = myValue - (int)myValue;
var str = decimalPart.ToString("0.0000000");
i found the solution. You use the float function.
int double= Convert.ToDouble(Console.ReadLine());
Console.WriteLine($"{num:fn}");
f specifies a float
n specifies the number of decimal places.
so f4 = to 4 decimal places

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

Convert String With Zeros To Decimal

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

Adding leading zero to value less than 1

Given a decimal value, how can I add a leading zero in a string only when a value is less than 1?
Eg.
.20 -> "0.20" - Add a leading 0
1.20 -> "1.20" - Value remains the same
The value before the decimal place could be of any length and the value after the decimal place will only be 2 digits ie. currency. Is this achievable with String.Format()? Or should I rely on a basic if statement?
The String.Format() documentation is rather confusing to me.
I've checked several other questions/answers and can't seem to find what I'm looking for.
EDIT: As mentioned by several answers, this kind of leading zero addition should be the default behavior of the ToString() method called on a value. For whatever reason, that isn't happening in my case, so The String.Format() is necessary in my case.
It is possible with string.format():
string.Format("{0:0.00}", 0.2) // 0.20
string.Format("{0:0.00}", 1.20) // 1.20
You can also use ToString() on the variables themselves:
var d1 = 0.2;
var d2 = 1.20;
Console.WriteLine(d1.ToString("0.00")); // 0.20
Console.WriteLine(d2.ToString("0.00")); // 1.20
If you use zero before a dot in the format string, you would get the desired effect:
string.Format("{0:0.00}", currency);
or using C# 6 syntax
$"{currency:0.00}"
Note that .NET also provides a generic format specifier for formatting currency, which takes care of leading zero as well:
$"{currency:C}"
What you are asking for is actually the default behavior of ToString() for a decimal type. You dont need String.Format().
decimal d = .20M;
string s = d.ToString();
Console.WriteLine(s);
All the other prior answers would be the preferred way to do what you're attempting. But here is an alternative to using string format specifiers.
var valStrVersion = ((val < 1.0M) ? "0" + val.ToString() : val.ToString());
And then you could whatever it is you need to do with it. Convert it back, print it out, whatever. Are you appending M to your decimal value when you declare it? decimal dec = 0.15M;?

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

Categories

Resources