Verify and print double value in 2 decimal places - c#

I am reading a string value and try to confirm its value its currency value via this method
double value;
if (!double.TryParse(sumValue, out value) || Math.Round(value, 2) != value)
{
MessageBox.Show("Not a double value");
}
This works fine. The issue when I use this MessageBox.Show(Math.Round(value, 2)) it does not show the value in 2 decimal places. What changes can I do for that and also am I using the right method to verify?

How the value is output will depend on the actual value.
While Math.Round(value, 2) will round the value to two decimal places, if that rounded value is 1.00 or 1.50 (for example) it will be displayed as "1" or "1.5" as the trailing zeros are omitted by default.
If you want to display the value to 2 decimal places then there are a number of ways to do this. All require you to call either string.Format or explicitly call .ToString with a format parameter.
One is to use:
MessageBox.Show(String.Format("{0:0.00}", value));
The first "0" represents the number itself and the the "0.00" indicates to the formatting engine that this is a floating point number with two decimal places. You can use "#:##" instead.
Source
Another is:
MessageBox.Show(value.ToString("F"));
Which is the fixed point format specifier. Adding a number specifies the number of decimal places (2 is the default). Source
Given that you say of your code that "This works fine." then your verification step is correct. You are checking that the value is a number and that the value rounded to 2 decimal places is the value you want. There's nothing more you need to do.

You can try to use .ToString() method with custom format, like this:
value.ToString("#.##");

Just use the code
MessageBox.Show(Convert.ToString(Math.Round(value, 2)));

Related

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

Double.Parse precision/Rounding issue

I have one column in database with datatype
decimal(24,10)
Let suppose I have value like
string d1 = "123.6666666666";
Double.Parse(d1)
output in datacolumn : 123.6666666700
I have used Convert.ToDecimal(d1) which gives output 123.6666666666.
Expected output :123.7000000000
The output you got is because the precision of double and decimal values. What you actualy want is to round the number to 1 fractional digit, for that you have to use Math.Round, either with a double or decimal, according to your needs, like this:
Math.Round(Double.Parse(d1),1)
Or, if you need
Math.Round(Convert.ToDecimal(d1),1)
For more information about Math.Round, check the MSDN link:
https://msdn.microsoft.com/pt-br/library/75ks3aby(v=vs.110).aspx

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

Double to String Format text format

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

Doing a Math.Round(x,2) on a decimal value, but need to ensure 2 numbers after decimal as its money

Some values are returning 2.0 but I need it to be 2.00 as this is a money value that is displayed to the web page.
I am doing:
Math.Round(value, 2);
Is there a way to force it to 2 numbers after the decimal?
You should be using a decimal to store monetary values.
But regardless of whether you are using a decimal or floating point type, your question asks how the number can be displayed with two decimal places. Use money.ToString("0.00") to display two decimal places.
If your using VB.Net use
FormatNumber(number, digitsAfter)
or
FormatCurrency(number, digitsAfter)
or this can be in both (C# and Vb.Net)
doubleNumber = -1898300.1987;
Console.WriteLine(doubleNumber.ToString("F2", CultureInfo.InvariantCulture));
// Displays -1898300.20
See this link for the full ToString() formats: http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx
Either .ToString("0.00") as Mark suggested if you only need to display .00
or Math.Round(value * 100.0) / 100.0; if you need an actual value with cent accuracy.

Categories

Resources