How to preserve the 2 digit precision - c#

I'm struggling to find a better way to preserve the 2 digit precision for decimal variable.
Here I have divided the question in 2 steps:
Step1: SQL Query
Inorder to get a 2 digit precision in a SQL query, I'm using
CONVERT(DECIMAL(10,2), .....) // to get 2 digit precision
On execution, I'm able to achieve the 2 digit precision in my SSMS.
NET_TOTAL
---------
10.00
12.50
14.25
Step2: via C# code
Whereas in my C# code, when I tried to store the value in my C# code it is not preserving the 2 digit precision.
NET_TOTAL
---------
10 //lost my precision
12.5 //lost my precision
14.25
Following is my variable declaration.
public decimal? NET_TOTAL { get; set; }
But I can smell a workaround using properties, but I'm not able to get it.
I'm using
dapper.net for database operations.
FileHelper.dll for converting the query list to a CSV file.
I would like to know the reason and a way to solve this problem.
Any help is much appreciated.
Thanks in advance.

Trailing zeros to the right of the decimal is not precision.
It is just presentation.
decimal d;
d = 10;
System.Diagnostics.Debug.WriteLine(string.Format("{0:N2}",d));

You can use
decimal.Round(value,decimalPoints);
This will return a decimal rounded upto decimalPoints.

You are confusing precision with representation. What you see in SSMS is a formatted number (a string). What you have in C# (and inside the DB) is a "true" number. In a true normally ending 0 after the decimal point aren't included.
If you want to format it you can do something like NET_TOTAL.ToString("0.00")
Note that there could be another problem:
NET_TOTAL = 1.245;
decimal sum = NET_TOTAL + NET_TOTAL;
the sum will be 2.29, but after a roundtrip to the DB NET_TOTAL will be 1.24 or 1.25 (depending on how the DB rounded 1.245) and the recalculated sum will be 2.28 or 2.3 .

is this acceptable:
private decimal? _netTotal;
public decimal? NET_TOTAL{
get{
return _netTotal;
}
set
{
if (value.HasValue)
{
_netTotal = Math.Truncate(value.Value, 2); // or rounding
}else{
_netTotal = value;
}
}
}
if you want to keep the original value but present it with 2 decimal places, then you could modify the getter instead: return Math.Truncate(value.Value, 2);

Related

Keep one number after decimal point, not rounding

I have a double variable in c#:
DoubleVar = 3.488;
I want to keep only one digit after decimal point, not rounding. For example:
3.4
Thanks so much in advance.
Since you specified "no rounding", and did not specify that this was being displayed as text. Then the following will Truncate to 1 decimal place
value = Math.Truncate(value * 10) / 10
Note: with floats you are likely going to get artefacts anyway, as there are numbers which can't be represented in base 2.
public static void Main()
{
double val = 1.33;
Console.WriteLine(String.Format("{0:0.#}", val));
}

Rounding to 2 decimal places 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.

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