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"));
Related
A web app I'm working on (another dev wrote it) has a decimal variable that is dropping two zero's after the decimal. It does not drop the trailing 2 digits if they contain a number > 0 or a combination of. The value is coming from a text file.
Example text value is: 261.00
Example decimal variable (TotalDue) is: 261
During debug when I hover over the "TotalDue" (in sample code below) the value displays as 261 and when I expand the debugger it reads "261M":
decimal TotalDue = Convert.ToDecimal(InputRow.Substring(260, 12));
I have tried bringing it in as a string (but initially it still reads as "261" instead of 261.00) and then converting it in various ways as follows. Nothing is working!
string TotalDue = InputRow.Substring(260, 12);
strTotalDue = String.Format("{0:F2}", TotalDue);
strTotalDue = String.Format("{0:N2}", TotalDue);
strTotalDue = String.Format(TotalDue, "0.00");
strTotalDue = TotalDue.ToString("G29");
strTotalDue = String.Format("{0:0.00}", TotalDue);
strTotalDue = TotalDue.ToString("N2");//used this one with decimal data type
What am I missing? Does it matter where the text file data originated? It started in an Access database.
UPDATE: Today (12/1/15) I realized I never marked an answer because I ended up scrapping the original code and rewriting it in C#.net. I will mark Cole Campbell's answer correct because his remarks ("construct the Decimal in a way that provides it with sufficient data regarding the precision of the input.") are what prompted me to come up with the solution I did which was to manipulate the incoming data. I did so in a method - only showing the part that matters (AmtDue) below. Reminder the incoming data was in the format of "261.00" (e.g. AmtDue = 261.00):
string AmtDue = Convert.ToString(AmountDue).Replace(".", "");
string finalstring = ("0000000000" + AmtDue).Substring(AmtDue.Length);
If you want two decimal places you can use the proper ToString:
string formatted = TotalDue.ToString("0.00");
> Demo <
Standard Numeric Format Strings
(by the way, ToString("D2") doesn't work)
The reason your first example is dropping the zeroes likely has to do with how you're creating the Decimal instance. Decimal contains a scaling factor which influences how ToString() works, and this scaling factor is set differently based on how the Decimal is constructed.
This code:
var d1 = Decimal.Parse("261.00");
var d2 = new Decimal(261.00);
var d3 = 261.00m;
Console.WriteLine(d1);
Console.WriteLine(d2);
Console.WriteLine(d3);
Produces these results:
261.00
261
261.00
If you want to preserve the trailing zeroes, construct the Decimal in a way that provides it with sufficient data regarding the precision of the input.
Remember that, as noted by other answers, the string provided by the debugger is not necessarily the same as the string produced by ToString().
The number you see in the debugger is not connected to how it actually displays in any way. 261M is correct - It's a value of "261", stored in decimal ("M" = "Money" = decimal) format.
Try the numeric formatting codes here. "F2" is what you want.
I'm sure you can google, and have likely come across this link, but here it is for reference:
String Formatting Doubles
It appears as if you've already tried strTotalDue = String.Format("{0:0.00}", TotalDue); so I'm not sure what else is going wrong.
Without more context however we won't know how to solve this issue.
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;
}
Basically, I have this really simple calculation:
int bTaxPrice = int.Parse(prices[wep]);
double t = double.Parse("1." + taxes);
double price = Math.Round(t * bTaxPrice);
I'll give you an example for how the calculation should work, lets say t=1.1 and bTaxPrice=1279, then 1.1*1279 = 1406.9, but since I'm rounding the result the price equals 1407.
For some users from another country (Denmark) that are using my C# Winforms program are experiencing a problem that causes the number not to round, but to add the last 2 digits after the decimal point.
Our result for the calculation above was 1407, for them it's 140690.
I read about it in the internet, and some countries have something special with there decimal point.
What is a good fix for this kind of issue?
Actually, many countries use a comma for their decimal separator.
If you want to use the dot as a separator, use the invariant CultureInfo:
double.Parse("1." + taxes, CultureInfo.InvariantCulture);
Some countries use a comma as decimal separator. You could fix this by supplying CultureInfo.InvariantCulture to the double.Parse method.
priceTotal.Text = (float.Parse(priceLiter.Text) * float.Parse(litres.Text)).ToString();
This somehow works fine on windows phone emulator, however, on the phone, it completely ignores the decimal points and multiplies as if the numbers were integers.
On emulator the priceLiter is initially parsed from a number (1.442) and converted to string so it can be put in a TextBox. On emulator, it converts it to
1.442
on the phone it converts it to
1,442
(notice the different decimal point)
However, the InputScope="Number" only displays the decimal point, and not a comma
Because of this, the priceTotal is calculated correctly on the emulator, but on the phone it ignores the decimal point . and treats it as thousands separator (I guess?), to state the obvious, the priceTotal is way off.
After some research, ss I expected, this depends on the Regional Format, and numeric keypad doesn't seem to be localized.
How can I approach this? Do I replace the entered decimal point with localized decimal point while text is still being input, if that is even possible?
Should I automatically replace all commas with dots before parsing numbers?
I could change InputScope to normal, but that wouldn't really change anything because half of people would enter the number using dot and other half using comma.
Thanks!
You could either force the current culture to US:
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("en-US");
Or you could give it as a parameter to the parsing method:
float.Parse(a, CultureInfo.GetCultureInfo("en-US"));
Another way to think about it is that you should parse it as you receive it. When a user has set his phone to dutch he would expect to use the , as the decimal mark.
This might be due to your phones culture.
Just write these 2 lines of code on your app.xaml.cs constructor
Thread.CurrentThread.CurrentCulture = (CultureInfo)Thread.CurrentThread.CurrentCulture.Clone();
Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator = ".";
The problem would never occur again.
i have the follwing lines of code
double formId=2013519115027601;
txtEditFormID.Text = formid.ToString();
it gives me output
2.0135191150276E+15
if i write
txtEditFormID.Text = formId.ToString("0.0", CultureInfo.InvariantCulture);
it gives me
2013519115027600.0
but i want the label text
2013519115027601
how to do it?
I don't have enough information about the usage of your formId variable.
As it is shown above it seems an error to use a double datatype when there is no decimals to work on. So redefining your variable as a long datatype will be easy and the conversion will be the same.
long formId=2013519115027601;
txtEditFormID.Text = formid.ToString();
Not to mention the added benefit to your code to work with whole numbers instead of floating point numbers.
However, if you want to maintain the current datatype then
txtEditFormID.Text = formId.ToString("R");
The Round Trip Format Specifier
When a Single or Double value is formatted using this specifier, it is
first tested using the general format, with 15 digits of precision for
a Double and 7 digits of precision for a Single. If the value is
successfully parsed back to the same numeric value, it is formatted
using the general format specifier. If the value is not successfully
parsed back to the same numeric value, it is formatted using 17 digits
of precision for a Double and 9 digits of precision for a Single.
Your first option is to use data type as long or decimal . Something else you can do if you want to keep using double is this :
double formId = 2013519115027601;
string text = formId.ToString();
txtEditFormID.Text = text.Replace(".",string.Empty);
this will remove all the '.' chars
There are times where I want calculations handled in double but I want the result displayed as as an int or even rounded amount, so the question isn't so strange (assuming that the given sample is simplified in order to ask the question).
I was going to post sample code for rounding, but it makes more sense to just use the built-in method Math.Round(). You can cast to a long, as mentioned above, but you won't have rounding, if desired (which it usually is, IMHO).
txtEditFormId.Text = ((long)formId).ToString();