Rounding to 2 decimal places c# - c#

Currently have a working rounding model within my c# code and is perfectly rounding numbers that have more than 2 decimal places down to 2 decimal places which is great. However, when i have lets say double value = 100.6, and i put that into double dollar_value = Math.Round(value, 2), it still returns as 100.6.
I was wondering if there was a way to transform a 1 decimal place value to 2 decimal places?

Numbers are not stored with extra zeroes (As it is a waste of memory to do so, being the numbers are the same with or without). In order to represent a number this way you will either need to display or store it as a string.
string str = value.ToString("#.00", CultureInfo.InvariantCulture);
Now str will always have 2 decimal places.

I don't know the C# method, but in C++ I'd use one of these two methods:
double value = 23.666666 ; // example
value = 0.01 * floor ( value * 100.0 ) ; // There's a "floor" function in C# too
^ See https://msdn.microsoft.com/en-us/library/e0b5f0xb(v=vs.110).aspx
Or
double value = 23.666666 ; // example
value = 0.01 * (double) ( (int)(value*100.0) ) ;
Or
double value = 23.666666 ; // example
value = 0.01 * double ( int ( value*100.0 ) ) ; // same as previous, but more C++ like
The other answers are probably better if you're looking to "print a dollar amount with two decimal places." However, if you want to transform the number to use internally, this is a way to do it.

If you want the string representation to have two decimal points use:
yourNumber.ToString ("0.00");
The number itself is always stored as a ~29 digit number regardless of its string representation.

Your value just needs to be formatted when it's display - for example value.ToString("N2") will convert it to a string with two decimal places. Check out the Standard Numeric Format Strings on MSDN to see a broader list of formatting strings.
Additionally, I'd only convert to a string when you're ready display the value to a user and would keep it as a numeric type (e.g. double) if you're passing it around between methods or planning to do any further calculations on it. Otherwise you'll be unnecessarily converting the value to and from a string multiple times.

Related

float invalid conversion / float unexpected behavior

I'm trying t wrap my mind around the float behavior (in C#). I have take notice of the floating point precision issue thingy.
I want to convert an floating point string to an float, add + 1 to it and convert it back to a string. The input can be with (never more then 5 decimal places) or without decimals, this is different every time. The output has to be again the full notation (no Scientific notation like: 2.017002E+09F)
It seems to work correctly with the decimal conversion.
Any suggestions for the best practice to get it working with a float?
var inputDecimalStr = "2017002005"; //2017002005.55 has the same result for the float conversion
float floatRegNr = 0;
float.TryParse(inputDecimalStr, out floatRegNr); // somehow this converts to 2.017002E+09
decimal test1 = decimal.Parse(inputDecimalStr); // this seems to work
float test2 = Convert.ToSingle(test1); // somehow this converts to 2.017002E+09
float test3 = Single.Parse(inputDecimalStr, NumberStyles.Float, CultureInfo.InvariantCulture);
float test4 = 2017002005F;
float test5 = 2.017002E+09F;
float test6 = 2.017002005E+09F;
double test7 = 234423.33D;
//this works ok
test5.ToString("0." + new string('#', 339));
test1.ToString();
If you use this tool that shows you the binary representation of float, you get that 2017002005 is represented as 0x4ef07204, which translated back to decimal form becomes 2017001984 (an error of 21 out of the conversion).
If you change the least significative bit of the number (i.e. the minimum change that can be registered) you get 0x4ef07205, which represents 2017002112 (107 more than 2017002005 + 1.
If this level of detail is important, you can use fixed point arithmetic. Since you only want to add 1, split the number into integer and decimal parts, add 1 to the integer part and then convert back to String each part separately.

Is there any drawback if i convert a string to Double then compare the result to integer value (such as 2000, 1000)

I am not sure if i am doing things correctly inside my asp.net application. now i have 3 fields which represents currency fields, which allow maximum of 2 decimals:-
OneTimeCost
MonthlyCost
AnnualCost
and i am calculating this value:-
var totalcost = double.Parse(currentItem["OnTimeCost"].ToString()) + (double.Parse(currentItem["MonthlyCost"].ToString()) * 12) + double.Parse(currentItem["AnnualCost"].ToString());
then i am comparing the result as follow:-
if( totalcost >= 2000)
{
}
else if (totalcost > 1000)
{
}
//and so on
Now i am not sure if i am doing things correctly or not? now the 3 fields i have, represents currency values which can allow 2 decimal points. so not sure if converting my values to double and then compare the result to integer values (2000 and 1000) is a correct and safe operation?
second question. is it better to use decimal.parse instead of double.parse? since decimal is more appropriate for financial calculations ?
so not sure if converting my values to double and then compare the
result to integer values (2000 and 1000) is a correct and safe
operation?
Yes, it's safe.
second question. is it better to use decimal.parse instead of
double.parse? since decimal is more appropriate for financial
calculations ?
if you're dealing with money then use decimal as that's why it's there.

Float to String Conversion

I want to convert float value to string.
Below is the code which i am using for the conversion.
static void Main(string[] args)
{
string s =string.Format("{0:G}", value);
Console.Write(s);
Console.ReadLine();
}
and it outputs as 2.5
But my problem is i want to get the value as 2.50 because i want to compare it with original value later in my project.
so please suggest me if there are any ways to do it?
You should be using {0:N2} to format to two decimal places.
string.Format("{0:N2}", 2.50)
For 3 decimal places:
string.Format("{0:N3}", 2.50)
And so on.
You can also store the value in a string this way without worrying about precision and then convert your value where you are testing for comparison as string:
string strDecimalVal = Convert.ToString( 2.5000001);
because i want to compare it with original value later in my project.
...then you will need to store the number of decimal places the original value had. Once the value is a float, this information is lost. The float representations of 2.5, 2.50 and 2.500 are exactly the same.
So, basically, you have the following possibilities (in order of preference):
Don't do a string comparison between the old and the new value. Convert both values to float and then compare them (with a margin of error since floats are not precise).
Store the number of decimal places of the old value and then use myFloat.ToString("F" + numDecimals.ToString()) to convert it to a string.
Store the value as a string instead of a float. Obviously, you won't be able to do math on that value.
Alternatively, if you do not insist on using floats, decimals might suit your purpose: The do store the number of significant digits:
decimal x = Decimal.Parse("2.50", CultureInfo.InvariantCulture);
decimal y = Decimal.Parse("2.500", CultureInfo.InvariantCulture);
Console.WriteLine(x.ToString()); // prints 2.50
Console.WriteLine(y.ToString()); // prints 2.500
Try this
Console.WriteLine("{0:F2}", 2.50);
Console.WriteLine("{0:0.00}", 2.50);
Console.WriteLine("{0:N2}", 2.50);
Version 1 and 2 are almost similar, but 3 is different. 3 will include number separators when number is large.
For example the following outputs 454,542.50
Console.WriteLine("{0:N2}", 454542.50);
More on MSDN

Converting a Decimal to a string equivalent

I am working with a decimal type in my application and have to submit that value as a string to a legacy web service which accepts values as strings. Its a payment value, so:
1000 => "100000" (1000 dollars and 00 cents)
131.11 => "13111"
I thought I'd multiply by 100 initially but ran into some cases that don't work as expected.
EDIT:
OK I will clarify:
decimal val = 145.99m;
Console.WriteLine((val * 100).ToString());
results in:
14599.00
but I really need 14599 without the decimal points, since the value the other side is expecting is 145 dollars and 99 cents.
I was thinking there may be a different way rather than doing something like String.Replace(".00", string.Empty) or is this the only way?
If you want it to be 0 decimal places, you can do myDecimal.ToString("0");.
For example:
decimal myDecimal = 25.99m;
(myDecimal*100m).ToString("0"); // 2599
While if your decimal had more decimal places:
decimal myDecimal = 3.14159m;
(myDecimal*100m).ToString("0"); // 314
EDIT: If your decimal has extra decimal places, it performs an .5 away round. (in my experience, VS2008).
You could simply convert to float, divide by 100, and convert to string then (supposing you store the number as an integer).
You could multiply by 100 then cast it to an integer based (integer in the mathematical sense) to truncate the decimal portion, and then ToString() the result.
decimal x = 45.13m;
string output = ((long)(x * 100)).ToString();

two decimal places for decimal/money field

I have a table with money field in my database. I have created entity and created decimal property for that money field. When the value of that field is displayed on My MVC3 view, It has four zeros 0000 after decimal like this : 5489.0000. I want to show only two 00 or decimal places. How can I fix it. Why it is showing four decimal places even I declared property as decimal.
Please suggest.
The SQL Server money datatype internally is a 64-bit integer with an implied scale of 4 decimal places. To quote Books Online, it is accurate "to ten-thousandsth of a currency unit." It is, the rough equivalent of a decimal(19,4).
The reason for the scale of 4 rather than 2 is to maintain precision in the results of arithmetic. Your ordinary currency value has a scale of 2 (e.g. $3.27) Multiplication or division of two numbers scaled to 2 decimal places gives a results that is precise to 4 decimal places: 9.23 divided by 3.27 yields a result of 2.82262996941896 (approximately). You can carry the result to whatever accuracy (number of decimal places) you desire. However, the result is only precise to 4 decimal places (2.8226) as the original values were only precise to 2 decimal places. That measurement is precise to within 1/2 of the smallest unit specified (+/- 0.005).
But I digress.
As a result of a SQL Server money value having an implied scale of 4, ADO.Net converts the value to a System.Decimal with a scale of 4. And since System.Decimal tracks scale, when you convert it to string, you get 4 decimal places.
To get fewer, you can
Round it before conversion, using the appropriate Decimal.Round() overload, or
Format it as desired (eg. (3.27M).ToString("0.00") ;.
Hope this helps.
This program:
namespace Sandbox
{
using System ;
class Program
{
static void Main( string[] args )
{
decimal pi = (decimal) Math.PI ;
string piText = pi.ToString("0.00");
Console.WriteLine("PI to 2 decimal places is {0} one way, and {1:0.00} another" , piText , pi ) ;
return;
}
}
}
Produces what you'd expect:
PI to 2 decimal places is 3.14 one way, and 3.14 another
Cheers,
N.
You have to format the string.
One thing you can do if it money you want to display is:
static void Main ()
{
decimal x = 0.999m;
decimal y = 9999999999999999999999999999m;
Console.WriteLine("My amount = {0:C}", x);
Console.WriteLine("Your amount = {0:C}", y);
}
}
OUTPUT:
Output
My amount = $1.00
Your amount = $9,999,999,999,999,999,999,999,999,999.00
the {0:C} is the currency Format
Hope this helps!
Here is everything you need to know about formatting strings.
http://blog.stevex.net/string-formatting-in-csharp/
I used this and it worked:
YourDecField.ToString("N")

Categories

Resources