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
Related
Can't find simple way to convert double to string. I need to convert large numbers without distortion. Such as:
double d = 11111111111111111111;
string s = d.ToString();
Console.WriteLine(s);
//1.11111111111111E+19
How to get string value from double value exactly the same as user enter.
11111111111111111111111 => "11111111111111111111111"
1.111111111111111111111 => "1.111111111111111111111"
Any ideas how it can be done?
double is a floating point type. So it has a limited accuracy. In your example, you could do something like this:
double d = 11111111111111111111;
string s = d.ToString("F0");
Console.WriteLine(s);
But as you'll see,this would output 11111111111111100000 instead of 11111111111111111111,so it has lost accuracy in the process. So the answer here is use the right type for the work. If you need a string, use a string variable to store the value.
Edit
This was the question i was trying to find that explains the problem with floating point math., thanks to #GSerg
First of all: 11111111111111111111111 is to large for a double value and also this value: 1.111111111111111111111 since the double max decimal length is 17.
By default, a Double value contains 15 decimal digits of precision,
although a maximum of 17 digits is maintained internally.
For this reason you should use BigInteger and then ToString for formatting the output.
There is also a library in the nuget Directory called BigRational, never used and seems in Beta stage but probably will help in solving this problem.
In general case, you can't do this: user can well input, say 123, in many a way:
123
123.00
1.23e2
12.3E1
123.0e+00
1230e-1
etc. When you convert the user input into double you loose the initial format:
string userInput = ...
// double is just 123.0 whatever input has been
double value = double.Parse(userInput);
In case you want to drop exponent if it's possible you can
double value = 11111111111111111111;
string result = value.ToString("#######################");
And, please, notice, that double has 64 bit to store the value, that's why a distortion is inevitable for large numbers:
// possible double, which will be rounded up
double big = 123456789123456789123456789.0;
// 1.2345678912345679E+26
Console.WriteLine(big.ToString("R"));
// 123456789123457000000000000
Console.WriteLine(big.ToString("###########################"));
May be you want BigInteger instead of double:
using System.Numerics;
...
BigInteger value = BigInteger.Parse("111111111111111111111111111111111");
// 111111111111111111111111111111111
Console.WriteLine(value.ToString());
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.
I have a string that can be up to 9 characters long including an optional decimal point but all the others will be numbers. It could be "123456789" or "12.345678", for example.
What variable type should I convert it to so that I can use it in calculations?
And how do I do that?
float.Parse("12.345678");
or
float.Parse("12.345678", CultureInfo.InvariantCulture.NumberFormat);
For avoiding these kind of outputs:
1.524157875019e+16
8.10000007371e-9
For integers you can checkout this link also: https://msdn.microsoft.com/en-us/library/bb397679.aspx
You should convert it to float, double or decimal, depending on how big the numbers become.
You can use Parse() or TryParse() to parse a string to an arithmetic type.
string numberString = "123456789";
double number;
if (!double.TryParse(numberString, out number))
{
// There was an error parsing ...
// Ex. report the error back or whatever ...
// You can also set a default value for it ...
// Ex. number = 0;
}
// Use number ...
It's a question of precision and a bit of memory consumption.
if the floating point remainder is important to you use one of the following:
float - 4 bytes, 7 digits precision
Double - 8 bytes, 15-16 digits precision
Decimal - 16 bytes , 28-29 digits precision
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);
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")