Why I have different result conversion text to double - c#

I have code here which will convert String value to Double with 2 decimal places. When the myStrValue is 820 the final result is 8.2 - which is wrong result it should be 8.20
I have code here:
string myStrValue = "820";
double myDblValue = Convert.ToDouble(myStrValue) * 0.01;
double finalValue = Math.Round(myDblValue, 2);
How to correct it?

final result is 8.2 - which is wrong result it should be 8.20
please don't mix up the number at hand and it's represenation as string when you display it. Mathematically 8.2 and 8.20 are the same numbers and are treated the same way.
On the other hand the string representation is controled by you when you decide to display it.
You can determine the format of display in different ways:
finalValue.ToString("0.00");
string rep = $"{finalValue:0.00}";
// and many more, google will find it
so there are no chance to make it 8.20? in double datatype?
Actually NO, because in datatype double it is saved entirely different, with an exponent and mantissa. If you are interested have a look at this page
But the representation of it will have no effect if you want to use the number.
Because finalValue + 0.001 will result in 8.201.

Related

C# formatting a number with thousand separators but keeping the decimal places count as is

I want to add a thousands separator to a double number but want to keep the decimal places as is i.e. dont want any rounding.
#,# is solving my problem of adding the thousand separator but how do I preserve the decimal places ? #,# strips off the part after ..
I cannot use any culture or something like that & the developer whose function I am calling has only given me a way of changing the format by passing as parameter strFormat.
I did check other posts & even the docs but somehow not able to figure this out.
string strFormat = "#,#";
string str = double.parse("912123456.1123465789").ToString(strFormat);
//Expected here 912,123,456.1123465789
//Actual Output 912,123,456
//912123456.123 should give 912,123,456.123
//912123456.1 should give 912,123,456.1
//912123456.1123465789 should give 912,123,456.1123465789
//912123456 should give 912,123,456
Well, after looking at the documentation on Microsoft, it would appear that there is no particular way to allow a floating point position in a number - all characters in a format string are character placeholders.
I would recommend that you either use a very nasty predetermined number of #s to set the width of the decimal position, or the slightly less (or possibly more, depending on your outlook) nasty option of reading all numbers into an array, determining the longest decimal position, then building a format of #s using the result.
At the end of the day, this is a single format string that you can put into place, test and ensure it works, then come back later and fix if you find a better alternative.
Also, this is one of those things where you could put the string into a configuration setting and change as and when you need to - far more flexible.
To be honest, this is a very slight thing to be worried about in the grand scheme of performance and writing a program.
Technically, Udi Y gets my vote!
If you know the max number of decimal places, e.g. 10, then use:
string strFormat = "#,#0.##########";
Update:
This max number is known.
According to Microsoft documentation a Double value has up to 15 decimal digits of precision (including both before and after the decimal point). More than 15 digits will be rounded.
So if you must invoke that method of 'double.parse' and can only send the format, this is the best you can do:
string strFormat = "#,#0.###############";
You can calculate the formatting dynamically for each number:
public static void Main()
{
var number = 1234.12312323123;
var format = GetNumberFormat(number);
Console.WriteLine(number.ToString(format));
}
public static string GetNumberFormat(double number)
{
var numberAsString = number.ToString();
var decimalPartSize = numberAsString.Substring(numberAsString.LastIndexOf('.') + 1).Length;
return $"N{decimalPartSize}";
}
So
number = 1234.12312323123
will give you 1,234.12312323123. Works for negative numbers as well. Also, as we work with strings, there won't be any rounding errors or precision artifacts.

How to remove decimal part from a number in C#

I have number of type double.
double a = 12.00
I have to make it as 12 by removing .00
Please help me
Well 12 and 12.00 have exactly the same representation as double values. Are you trying to end up with a double or something else? (For example, you could cast to int, if you were convinced the value would be in the right range, and if the truncation effect is what you want.)
You might want to look at these methods too:
Math.Floor
Math.Ceiling
Math.Round (with variations for how to handle midpoints)
Math.Truncate
If you just need the integer part of the double then use explicit cast to int.
int number = (int) a;
You may use Convert.ToInt32 Method (Double), but this will round the number to the nearest integer.
value, rounded to the nearest 32-bit signed integer. If value is
halfway between two whole numbers, the even number is returned; that
is, 4.5 is converted to 4, and 5.5 is converted to 6.
Use Decimal.Truncate
It removes the fractional part from the decimal.
int i = (int)Decimal.Truncate(12.66m)
Use Math.Round
int d = (int) Math.Round(a, 0);
Reading all the comments by you, I think you are just trying to display it in a certain format rather than changing the value / casting it to int.
I think the easiest way to display 12.00 as "12" would be using string format specifiers.
double val = 12.00;
string displayed_value = val.ToString("N0"); // Output will be "12"
The best part about this solution is, that it will change 1200.00 to "1,200" (add a comma to it) which is very useful to display amount/money/price of something.
More information can be found here:
https://msdn.microsoft.com/en-us/library/kfsatb94(v=vs.110).aspx
here is a trick
a = double.Parse(a.ToString().Split(',')[0])
Because the numbers after point is only zero, the best solution is to use the Math.Round(MyNumber)
//I am doing a basic Calculation here and this works for me.
// it takes values from textboxes and performs the following as far as I understand it. as I have only been coding now for a few months.
double VC2 = Convert.ToDouble(txt_VC_M16_Tap.Text); // converts to double.
double total2 = (VC2 * 1000) / (3.14157 * 14.5); // performs the calculation.
total2 = Math.Round(total2); //Round the result to a whole number(integer)
txt_RPM2.Text = Convert.ToString(total2); // converts result to string and puts it in the textbox as required.
// Hope this helps people that are looking for simple answers.

Math-pow incorrect results

double a1;
a1 = Math.Pow(somehighnumber, 40);
something.Text = Convert.ToString(xyz);
the result i get is have E+41 etc.
its like 1,125123E+41 etc. i dont get why.
Your question is very unclear; in the future, you'll probably get better results if you post a clear question with a code sample that actually compiles and demonstrates the problem you're actually having. Don't make people guess what the problem is.
If what you want to do is display a double-precision floating point number without the scientific notation then use the standard number formatting specifier:
Console.WriteLine(string.Format("{0:N}", Math.Pow(10, 100)));
Results in:
10,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000.00
If what you have a problem with is that the result is rounded off, then don't use double-precision floats; they are accurate to only 15 decimal places. Try doing your arithmetic in BigIntegers, which have arbitrary integer precision.
That's scientific notation. It means 1.125123 * 1041. Scientific notation is useful if your number becomes so large that displaying it in full would require a lot of screen space. Also, floating point arithmetic is not precise so even if you did display the number in full most of the digits would be incorrect anyway.
If you want precise calculations you should use BigInteger instead of double (this type is present in .NET 4.0 or newer).
double bigNum = Math.Pow(100, 100);
string bigString = string.Format("{0:F}", bigNum);
http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx#FFormatString
Or you can use the 4.0 indroduced BigInteger(add a reference to System.Numerics to the Project):
Numerics.BigInteger bigInt = Numerics.BigInteger.Pow(1000, 1000);
string veryBigString = bigInt.ToString("F");
As you can see it also works with ToString.

Limiting double to 3 decimal places

This i what I am trying to achieve:
If a double has more than 3 decimal places, I want to truncate any decimal places beyond the third. (do not round.)
Eg.: 12.878999 -> 12.878
If a double has less than 3 decimals, leave unchanged
Eg.: 125 -> 125
89.24 -> 89.24
I came across this command:
double example = 12.34567;
double output = Math.Round(example, 3);
But I do not want to round. According to the command posted above,
12.34567 -> 12.346
I want to truncate the value so that it becomes: 12.345
Doubles don't have decimal places - they're not based on decimal digits to start with. You could get "the closest double to the current value when truncated to three decimal digits", but it still wouldn't be exactly the same. You'd be better off using decimal.
Having said that, if it's only the way that rounding happens that's a problem, you can use Math.Truncate(value * 1000) / 1000; which may do what you want. (You don't want rounding at all, by the sounds of it.) It's still potentially "dodgy" though, as the result still won't really just have three decimal places. If you did the same thing with a decimal value, however, it would work:
decimal m = 12.878999m;
m = Math.Truncate(m * 1000m) / 1000m;
Console.WriteLine(m); // 12.878
EDIT: As LBushkin pointed out, you should be clear between truncating for display purposes (which can usually be done in a format specifier) and truncating for further calculations (in which case the above should work).
I can't think of a reason to explicitly lose precision outside of display purposes. In that case, simply use string formatting.
double example = 12.34567;
Console.Out.WriteLine(example.ToString("#.000"));
double example = 3.1416789645;
double output = Convert.ToDouble(example.ToString("N3"));
Multiply by 1000 then use Truncate then divide by 1000.
If your purpose in truncating the digits is for display reasons, then you just just use an appropriate formatting when you convert the double to a string.
Methods like String.Format() and Console.WriteLine() (and others) allow you to limit the number of digits of precision a value is formatted with.
Attempting to "truncate" floating point numbers is ill advised - floating point numbers don't have a precise decimal representation in many cases. Applying an approach like scaling the number up, truncating it, and then scaling it down could easily change the value to something quite different from what you'd expected for the "truncated" value.
If you need precise decimal representations of a number you should be using decimal rather than double or float.
You can use:
double example = 12.34567;
double output = ( (double) ( (int) (example * 1000.0) ) ) / 1000.0 ;
Good answers above- if you're looking for something reusable here is the code. Note that you might want to check the decimal places value, and this may overflow.
public static decimal TruncateToDecimalPlace(this decimal numberToTruncate, int decimalPlaces)
{
decimal power = (decimal)(Math.Pow(10.0, (double)decimalPlaces));
return Math.Truncate((power * numberToTruncate)) / power;
}
In C lang:
double truncKeepDecimalPlaces(double value, int numDecimals)
{
int x = pow(10, numDecimals);
return (double)trunc(value * x) / x;
}

Get the decimal part of a number and the number of places after the decimal point (C#)

Does anyone know of an elegant way to get the decimal part of a number only? In particular I am looking to get the exact number of places after the decimal point so that the number can be formatted appropriately. I was wondering if there is away to do this without any kind of string extraction using the culture specific decimal separator....
For example
98.0 would be formatted as 98
98.20 would be formatted as 98.2
98.2765 would be formatted as 98.2765 etc.
It it's only for formatting purposes, just calling ToString will do the trick, I guess?
double d = (double)5 / 4;
Console.WriteLine(d.ToString()); // prints 1.75
d = (double)7 / 2;
Console.WriteLine(d.ToString()); // prints 3.5
d = 7;
Console.WriteLine(d.ToString()); // prints 7
That will, of course, format the number according to the current culture (meaning that the decimal sign, thousand separators and such will vary).
Update
As Clement H points out in the comments; if we are dealing with great numbers, at some point d.ToString() will return a string with scientific formatting instead (such as "1E+16" instead of "10000000000000000"). One way to overcome this probem, and force the full number to be printed, is to use d.ToString("0.#"), which will also result in the same output for lower numbers as the code sample above produces.
You can get all of the relevant information from the Decimal.GetBits method assuming you really mean System.Decimal. (If you're talking about decimal formatting of a float/double, please clarify the question.)
Basically GetBits will return you 4 integers in an array.
You can use the scaling factor (the fourth integer, after masking out the sign) to indicate the number of decimal places, but you should be aware that it's not necessarily the number of significant decimal places. In particular, the decimal representations of 1 and 1.0 are different (the former is 1/1, the latter is 10/10).
Unfortunately, manipulating the 96 bit integer is going to require some fiddly arithmetic unless you can use .NET 4.0 and BigInteger.
To be honest, you'll get a simpler solution by using the built in formatting with CultureInfo.InvariantCulture and then finding everything to the right of "."
Just to expand on the point about getbits, this expression gets the scaling factor from a decimal called foo:
(decimal.GetBits(foo)[3] & 16711680)>>16
You could use the Int() function to get the whole number component, then subtract from the original.

Categories