How to remove decimal part from a number in C# - 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.

Related

Convert double to time format

I'm new to ASP.NET MVC C# Programming
I have a class which contains an attribute called Credits of type double. This attribute should be represented as a Time Format (hh:mm) in my web application. So for example, if I were to give Credits the value of 2.5, I want it to display 2:50, 6.15 as 6:15, etc. I know TimeSpan can convert a double to the time format but it converts 2.5 to 2:30. Is there a way to do easily convert a double to this time format without changing its data type to a String? Is there some sort of helper Attribute tag or something that would make this easy?
It appears that you want to get the whole number and the fractional part separated, and that you want the fractional part as a two-digit number.
So here's how you would get the whole number part as an int.
var whole = (int)Math.Truncate(value);
And this would give you the fractional part as an int, in this case only the first two decimal places.
var twoFrac = (int)(((decimal)value % 1) * 100);
So, if value was 12.345, then twoFrac would turn out to be 34 in int.
Now you can display these whichever way you like.
And you can actually put the above inside of a method so you can get the fractional part up to however many decimal places you want, like this:
private static int GetFractionalPart(double value, int decimalPlaces)
{
var factor = (int)Math.Pow(10, decimalPlaces);
var fractional = (int)(((decimal)value % 1) * factor);
return fractional;
}
NOTE
However, as many others pointed out in comments, this is a confusing and you could even say wrong way of doing things if you're actually dealing with time values. For example, using your criteria, a value of 2.75 would convert to 2:75, but that doesn't mean anything in terms of time.
So you really ought to use TimeSpan as you mentioned in your original post, which would convert 2.5 to 2:30 etc.

Why I have different result conversion text to double

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.

.NET's ToString() Number Truncating

So, WPF calls ToString() on objects when generating TextColumns in DataGrid and then i found out strange thing about ToString() method:
Check this out :
object a = 0.3780000001;//Something like this
Console.WriteLine(a.ToString());//Gets truncated in some cases
First, I thought it was just rounding, but few times I was able to reproduce such behavior on
doubles with < 15 digits after dot. Am I missing something?
To the computer, 0.378 and 0.378000...0001 are the same number. See this question: Why is floating point arithmetic in C# imprecise?
As defined on the MSDN page for System.Double, the double type only contains a maximum of fifteen digits of precision. Even though it maintains 17 internally, your figure contains 18 significant digits; this is outside the range of System.Double.
Use decimal instead of float for a more precise type.
By default, Double.ToString() truncates to 15 digits after the dot, but if you really want to use the double data type and you need those 2 extra digits, you can use th "G17" formatting string:
double x = 3.1415926535897932;
string pi = x.ToString("G17");
This will give you a string with the full 17 digits.
I wouldn't assume (so fast) that you found a bug in something as crucial as C#'s ToString implementation.
The behaviour you're experiencing is caused by the fact that a float is imprecisely stored in computer memory (also see this question).
maybe the number format's accuracy range doesn't contain that number? (ie, float only has accuracy to a few significant figures)
If you're data-binding the value, you can supply a ValueConverter which formats the number any way you want.
http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.aspx
Set a to be an Decimal and it will print it correctly!
decimal a = 0.378000000000000001m;
Console.WriteLine(a.ToString());
You could have a common decimal format setting to use all the time.
eg
object a = 0.378000000000000001;
Console.WriteLine(a.ToString(Settings.DecimalFormat));

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;
}

How do I format a number in C# with commas and decimals?

I have a number with a variable number of digits after the decimal point. I want to format the number with commas and all decimal numbers.
For example: 42,023,212.0092343234
If I use ToString("N") I get only 2 decimals, ToString("f") gives me all decimals no commas. How do I get both?
Not sure (and unable to test right now) but would something like this work?
"#,##0.################"
string.Format("{0:#,##0.############}", value);
will give you up to 12 decimal places.
There is not a custom format specifier for "all following digits", so something like this will be closest to what you want.
Note too that you're limited by the precision of your variable. A double only has 15-16 digits of precision, so as your left-hand side gets bigger the number of decimal places will fall off.
UPDATE: Looking at the MSDN documentation on the System.Double type, I see this:
By default, a Double value contains 15
decimal digits of precision, although
a maximum of 17 digits is maintained
internally.
So I think pdr's on to something, actually. Just do this:
// As long as you've got at least 15 #s after the decimal point,
// you should be good.
value.ToString("#,#.###############");
Here's an idea:
static string Format(double value)
{
double wholePart = Math.Truncate(value);
double decimalPart = Math.Abs(value - wholePart);
return wholePart.ToString("N0") + decimalPart.ToString().TrimStart('0');
}
Example:
Console.WriteLine(Format(42023212.0092343234));
Output:
42,023,212.00923432409763336
Ha, well, as you can see, this gives imperfect results, due (I think) to floating point math issues. Oh well; it's an option, anyway.
Try ToString("N2")
Let's try this
[DisplayFormat(DataFormatString = "{0:0,0.00}")]
Here is the way somewhat to reach to your expectation...
decimal d = 42023212.0092343234M;
NumberFormatInfo nfi = (NumberFormatInfo) CultureInfo.InvariantCulture.NumberFormat.Clone();
nfi.NumberDecimalDigits= (d - Decimal.Truncate(d)).ToString().Length-2;
Console.WriteLine(d.ToString("N",nfi));
For more detail about NumberFormatInfo.. look at MSDN ..
http://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.aspx

Categories