In C#, is it possible to perform ToString on a float and get the value without using exponentials?
For example, consider the following:
float dummy;
dummy = 0.000006F;
Console.WriteLine(dummy.ToString());
This gives the output
6E-06
However, what I was is
0.000006
The closest I could find was using the "F" qualifier, however I then need to specify the number of decimal places otherwise the value get rounded.
Is there actually a way of doing this automatically or do I need to do a load of funky logic to either trim zeroes or figure out the number of required decimals.
Thanks;
Richard Moss
Try this
Console.WriteLine(dummy.ToString("F"));
You can also specify number of decimal places. For example F5, F3, etc.
Also, you can check custom format specifier
Console.WriteLine(dummy.ToString("0.#########"));
string dum = string.Format("{0:f99}",dummy).TrimEnd('0');
if (dum.EndsWith(",")) dum = dum.Remove(dum.Length - 1);
Without some further background info, it's hard to tell - but it sounds like you want decimal semantics. So why not use the decimal type instead?
decimal dummy;
dummy = 0.000006M;
The decimal type is more accurate at representing decimal numbers than float or double, but it is not as performant. See here for more info.
Console.WriteLine(dummy.ToString("N5"));
where 5 its number of decimal places
float dummy = 0.000006F;
Console.WriteLine(dummy.ToString("0." + new string('#', 60)));
If you'll be doing this a lot then it makes sense to store the format string in a static field/property somewhere and re-use it, rather than constructing a new string every time:
private static readonly string _allFloatDigits = "0." + new string('#', 60);
// ...
float dummy = 0.000006F;
Console.WriteLine(dummy.ToString(_allFloatDigits));
Related
I have the need to round a number for pricing sort of strangely as follows:
the value of an incoming price will be 3 decimal places (ie. 10.333)
It is necessary to round the first decimal place up if any number past said first decimal place is greater than 0.
for example:
10.300 = 10.3,
10.301 = 10.4,
10.333 = 10.4
before I go creating a custom method to do this I was wondering if anyone was aware of an existing usage/overload of Math.Round() or other already existing package to get this desired result?
Math.Round has an overload that accepts a MidpointRounding enum value, which lets you specify the strategy for rounding.
In your case, you always want to round up, which is called ToPositiveInfinity.
Math.Round(yourValue, 1, System.MidpointRounding.ToPositiveInfinity)
Approach with Math.Ceiling()
decimal input = 10.300m;
decimal result = Math.Ceiling(input * 10m) / 10m;
https://dotnetfiddle.net/Vck4Oa
double d = 10.300;
var result= Math.Ceiling((decimal)d * 10) / 10;
I have logging functionality in project which compares objects value and displays differences but i have a scenarion i have latitude and longitude values in double data type but when i concatenate it with string or convert it to string i am getting strange behaviour as it is showing the same value in both variables which is totally not understandable how it is happening.
Here is the code:
double value1 = -6.2845230102539063;
double value2 = -6.2845230102539098;
if (!object.Equals(value1, value2))
{
var result = value2 + " to " + value1;
Console.WriteLine(result);
}
Console.ReadLine();
Expected Output :
-6.2845230102539098 to -6.2845230102539063
Actual Output :
-6.28452301025391 to -6.28452301025391
Here is DEMO FIDDLE:
https://dotnetfiddle.net/0XM3Da
What is happening here?
From MSDN: http://msdn.microsoft.com/en-us/library/678hzkk9.aspx
Double has a precision of 15-16 digits. You've exceeded that limit. You should use Decimal instead. See here for details: Can C# store more precise data than doubles?
This is addressed in #LukeH's answer to "Formatting doubles for output in C#":
The problem is that .NET will always round a double to 15 significant
decimal digits before applying your formatting, regardless of the
precision requested by your format and regardless of the exact decimal
value of the binary number.
Using the DoubleConverter class linked to in that answer, we get
var x = -6.2845230102539063;
var y = -6.2845230102539098;
Console.WriteLine(x == y);
Console.WriteLine(x);
Console.WriteLine(y);
Console.WriteLine(DoubleConverter.ToExactString(x));
Console.WriteLine(DoubleConverter.ToExactString(y));
which prints
False
-6.28452301025391
-6.28452301025391
-6.28452301025390625
-6.284523010253909802713678800500929355621337890625
Or you can use the G17 format specification
Console.WriteLine(x.ToString("G17"));
Console.WriteLine(y.ToString("G17"));
which will give you
-6.2845230102539063
-6.2845230102539098
From: http://msdn.microsoft.com/en-us/library/kfsatb94(v=vs.110).aspx
'By default, the return value only contains 15 digits of precision although a maximum of 17 digits is maintained internally.'
So it knows that they are not the same size, but doesn't display them that way.
A Double value has up to 15 decimal digits of precision, you can refer to detail explanation http://msdn.microsoft.com/zh-cn/library/system.double(v=vs.110).aspx
Have you tried the decimal data type. It gives you an exact representation of numbers...for banking and stock markets I suppose. And you could reduce the mantissa to a certain length (perhaps 18).
I have a double var represnting the seconds passed since 01/01/1900 from an ntp server and it prints ok
3616290958.594
3616290959.611
3616290960.538
I tried to convert it to a float in different methods like System.Convert.ToSingle and regular casting but I always get
3,616,291,000.00
I print the float using it's .ToString("N") method if it makes a difference
I even tried converting the double to a long, then the long to the float (I don't need any precision data after the dot, I'm going to floor the double before converting anyway).
nothing works, help.
You can simply use Math.Truncate
Example:
Double d = 3616290958.594;
string k = Math.Truncate(d);
I have been searching forever and I simply cannot find the answer, none of them will work properly.
I want to turn a double like 0.33333333333 into 0,33 or 0.6666666666 into 0,66
Number like 0.9999999999 should become 1 though.
I tried various methods like
value.ToString("##.##", System.Globalization.CultureInfo.InvariantCulture)
It just returns garbage or rounds the number wrongly.
Any help please?
Basically every number is divided by 9, then it needs to be displayed with 2 decimal places without any rounding.
I have found a nice function that seems to work well with numbers up to 9.999999999
Beyond that it starts to lose one decimal number. With a number like 200.33333333333
its going to just display 200 instead of 200,33. Any fix for that guys?
Here it is:
string Truncate(double value, int precision)
{
string result = value.ToString();
int dot = result.IndexOf(',');
if (dot < 0)
{
return result;
}
int newLength = dot + precision + 1;
if (newLength == dot + 1)
{
newLength--;
}
if (newLength > result.Length)
{
newLength = result.Length;
}
return result.Substring(0, newLength);
}
Have you tried
Math.Round(0.33333333333, 2);
Update*
If you don't want the decimal rounded another thing you can do is change the double to a string and then get get a substring to two decimal places and convert it back to a double.
doubleString = double.toString();
if(doubleString.IndexOf(',') > -1)
{
doubleString = doubleString.Substring(0,doubleString.IndexOf(',')+3);
}
double = Convert.ToDouble(doubleString);
You can use a if statement to check for .99 and change it to 1 for that case.
Math.Truncate(value * 100)/100
Although I make no guarantees about how the division will affect the floating point number. Decimal numbers can often not be represented exactly in floating point, because they are stored as base 2, not base 10, so if you want to guarantee reliability, use a decimal, not a double.
Math.Round((decimal)number, 2)
Casting to a decimal first will avoid the precision issues discussed on the documentation page.
Math.Floor effectively drops anything after the decimal point. If you want to save two digits, do the glitch operation - multiply then divide:
Math.Floor(100 * number) / 100
This is faster and safer than doing a culture-dependent search for a comma in a double-converted-to-string, as accepted answer suggests.
you can try one from below.there are many way for this.
1.
value=Math.Round(123.4567, 2, MidpointRounding.AwayFromZero) //"123.46"
2.
inputvalue=Math.Round(123.4567, 2) //"123.46"
3.
String.Format("{0:0.00}", 123.4567); // "123.46"
4.
string.Format("{0:F2}", 123.456789); //123.46
string.Format("{0:F3}", 123.456789); //123.457
string.Format("{0:F4}", 123.456789); //123.4568
Using C#, I want to format a decimal to only display two decimal places and then I will take that decimal and subtract it to another decimal. I would like to be able to do this without having to turn it into a string first to format and then convert it back to a decimal. I'm sorry I forget to specify this but I don't want to round, I just want to chop off the last decimal point. Is there a way to do this?
If you don't want to round the decimal, you can use Decimal.Truncate. Unfortunately, it can only truncate ALL of the decimals. To solve this, you could multiply by 100, truncate and divide by 100, like this:
decimal d = ...;
d = Decimal.Truncate(d * 100) / 100;
And you could create an extension method if you are doing it enough times
public static class DecimalExtensions
{
public static decimal TruncateDecimal(this decimal #this, int places)
{
int multipler = (int)Math.Pow(10, places);
return Decimal.Truncate(#this * multipler) / multipler;
}
}
You can use: Math.Round(number,2); to round a number to two decimal places.
See this specific overload of Math.Round for examples.
Math.Round Method (Decimal, Int32)
You don't want to format it then, but to round it. Try the Math.Round function.
Take a look at Math.Round