I have to convert an object to int. My object values is something like 1.34535
What I need is the first part which is (1).
I tried the followings:
- Convert.ToInt32(myObj.Value), it rounds the number. if it's 1.78, I got it (2) which is wrong. I need only the integer of first part.
int.TryParse(myObj.Value.toString(), out outValue)
I got it 0 for all values!
int.Parse(myObj.Value.toString()) throws an exception, that is in incorrect format.
If myObj.Value is boxed double then you have to cast twice: to unbox back into double and then in order to truncate into int:
int result = (int)((double)(myObj.Value)):
In general case, try Convert; the idea is the same: first restore the orignal double and then obtain required int:
int result = (int) (Convert.ToDouble(myObj.Value));
Edit: in the implementation above I've read without rounding request as truncated, i.e. fractional part should be ignored:
2.4 -> 2
-2.4 -> -2
If different behaviour is expected, e.g.
2.4 -> 2
-2.4 -> -3
one can add Math.Floor e.g.
int result = (int) (Math.Floor(Convert.ToDouble(myObj.Value)));
Convert to double it first;
var doubleValue = double.Parse(myObj.Value.ToString());
//It could be better to use double.TryParse
int myInt = (int)Math.Floor(doubleValue);
Convert your object to a double value and use Use Math.Truncate(number)
http://msdn.microsoft.com/en-us/library/c2eabd70.aspx
Very easy, don't forget to wrap it in try and catch:
int i = (int)Math.Truncate(double.Parse(myObj.ToString()));
Math.Truncate just cuts off the numbers after the comma like:
4.434 becomes 4
-43.65445 becomes -43
Perhaps, this is also a solution :
var integer = int.Parse(myObject.Value.ToString().Split('.').First());
Related
I'm trying to cast the result of a divide result to an int in c#
This is my code:
decimal testDecimal = 5.00; // testDecimal always is dividable by 0.25 with 0 rest
int times=0;
int times = testDecimal / Convert.ToDecimal(0.250);
// error returned -> Cannot implicitly convert type 'decimal' to 'int'.
if I change my cast to
int times = (int) testDecimal / Convert.ToDecimal(0.250);
//also returns an error: Cannot implicitly convert type 'decimal' to 'int'
How could I get the result (20) as an integer? What am I doing wrong?
Try this:
times = (int)(testDecimal / Convert.ToDecimal(0.250));
Without the extra parenthesis, it is trying to convert ONLY testDecimal to integer, then trying to convert the int/decimal result to an integer implicitly, which is what causes the error.
In an unrelated note, you are trying to declare the variable 'times' twice.
As everybody answered, you have to add parenthesis to cast the result of the your division instead of just trying to cast the first part and then getting the error after the division.
I also want to point out that it is not necessary to use Convert.ToDecimal just to declare your constant as adecimal, you could use C# suffixs to do so:
int times = (int)(testDecimal / 0.250m);
You have to cast the whole division result. try like:
int times = (int) (testDecimal / Convert.ToDecimal(0.250));
Be careful though because this could suffer the seemingly random floating point arithmetic error depending on which values you use.
https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
You may avoid this by first rounding the value.
(int) Math.Round(testDecimal / Convert.ToDecimal(0.250));
first you don't need to do convert to decimal, you can just do 0.25m
and then you can do
times = (int) (testDecimal / 0.25m);
do note that if the number is too big this might give you wrong result.
If you want a numeric literal to be treated as decimal, use the suffix m or M. By this way there is no need to use Convert.ToDecimal.
decimal testDecimal = 5.00M;
int times = (int)(testDecimal / 0.250M);
First of all you should add "M" suffix to your testDecimal declaration otherwise your 5.00 is a litteral and not a decimal.
decimal testDecimal = 5.00M;
Now, your compiler is not aware that your division result is an integer. Even if your devision can be casted to "int", for him, a decimal devided by another is a decimal and not an integer. You have to implicitly cast it:
int times = (int)(testDecimal / 0.250M);
Works like charm for me.
Wrap your expression in parenthesis so that you can convert it:
// int times = (int)testDecimal / 0.250m;
int times = (int)(testDecimal / 0.250m);
Just a note, make sure you are try/catching while converting because not all decimal values can fit into int.
try
{
times = (int)decimal.MaxValue;
}
catch(OverflowException ex)
{
// Value was either too large or too small for an Int32.
}
I'm not sure why you have Convert.ToDecimal(0.250). Why convert the float (0.250) to a decimal at run time? Why not just use a decimal literal (like 0.25M)? As other folks have noted, you need to cast the results of the division to an int, like:
decimal testDecimal = 5M;
int times = (int) (testDecimal / 0.25M);
Assert.AreEqual(20, times);
Also, as other folks have noted, you may want to think through how you do your conversion from decimal to int. Do you want to the default behavior (what you get from a simple cast), or do you want round up, round down, round to even, etc.? In this case, since the division yields an integral result, it doesn't matter, but in the general case, you'll want to put some thought into it.
By the way, the reason you have an error in this code:
int times = (int) testDecimal / Convert.ToDecimal(0.250);
is that you are casting testDecimal (5.0M) to an int (5). Then you are dividing it by a decimal (0.25M), which yields a decimal (20.0M). Finally, you are trying to assign that decimal to an integer, and the compiler signals an error.
HTH
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());
8654 -> 8653; 1000 -> 0999; 0100 -> 0099; 0024 -> 0023; 0010 -> 0009; 0007 -> 0006 etc.
I have a string variable of fixed length 4; its characters are always numbers. I want to make subtraction while obeying the given rule that its length of 4 must be protected.
What I tried: Convert.ToInt32, .Length operations etc. In my code, I always faced some sort of errors.
I devised that I can do this via 3 steps:
1. Convert the string value to an (int) integer
2. Subtract "1" in that integer to find a new integer
3. Add "4 - length of new integer" times "0" to the beginning.
Anyway, independent of the plotted solution above (since I am a newbee; perhaps even my thought may divert a standard user from a normal plausible approach for solution), is not there a way to perform the above via a function or something else in C#?
A number doesn't have a format, it's string representation has a format.
The steps you outlined for performing the arithmetic and outputting the result are correct. I would suggest using PadLeft to output the result in the desired format:
int myInt = int.Parse("0100");
myInt = myInt - 1;
string output = myInt.ToString().PadLeft(4, '0');
//Will output 0099
Your steps are almost right, however there is a easier way to accomplish getting the leading 0's, use Numeric string formatting. Using the formatting string "D4" it will behave exactly like you want.
var oldString = "1000";
var oldNum = Convert.ToInt32(oldString);
var newNum = oldNum - 1;
var newString = newNum.ToString("D4");
Console.WriteLine(newString); //prints "0999"
Click to run example
You could also use the custom formatting string "0000".
Well, I think others have implemented what you have implemented already. The reason might be that you didn't post your code. But none of the answers addresses your main question...
Your approach is totally fine. To make it reusable, you need to put it into a method. A method can look like this:
private string SubtractOnePreserveLength(string originalNumber)
{
// 1. Convert the string value to an (int) integer
// 2. Subtract "1" in that integer to find a new integer
// 3. Add "4 - length of new integer" times "0" to the beginning.
return <result of step 3 >;
}
You can then use the method like this:
string result = SubtractOnePreserveLength("0100");
// result is 0099
Is it possible to use Convert.ToInt32(double) and make it choose the smallest value?
I've read the examples in msdn, it converts a double to int using the closest value, which means that if i have a double equal to 2.9 it would set the int to 3.
Is it possible to use convert.toint32 and use 2?
Use Math.Floor. See this link: https://msdn.microsoft.com/en-us/library/system.math.floor(v=vs.110).aspx
EDIT: Math.Floor returns a double, so you will have to cast it, such as int y = (int)Math.Floor(3.934333), which would return 3.
You can use just casting to int, you can check it:
double x = 2.9;
int y = (int) x;
Console.WriteLine (y); // 2
I have a number ("double") from int/int (such as 10/3).
What's the best way to Approximation by Excess and convert it to int on C#?
Are you asking about System.Math.Ceiling?
Math.Ceiling(0.2) == 1
Math.Ceiling(0.8) == 1
Math.Ceiling(2.6) == 3
Math.Ceiling(-1.4) == -1
int scaled = (int)Math.Ceiling( (double) 10 / 3 ) ;
By "Approximation by Excess", I assume you're trying to "round up" the number of type double. So, #Doug McClean's "ceiling" method works just fine.
Here is a note:
If you start with double x = 0.8; and you do the type conversion by (int)x; you get 0. Or, if you do (int)Math.Round(x); you get 1.
If you start with double y = 0.4; and you do the type conversion by (int)y; you get 0. Or, if you do (int)Math.Round(y); you get 0.
Consider 2.42 , you can say it's 242/100 btw you can simplify it to 121/50 .