Use Convert.ToInt32 from mscorlib as in
decimal value = 3.14m;
int n = Convert.ToInt32(value);
See MSDN. You can also use Decimal.ToInt32. Again, see MSDN. Finally, you can do a direct cast as in
decimal value = 3.14m;
int n = (int) value;
which uses the explicit cast operator. See MSDN.
Answer from jason on Stack OverflowUse Convert.ToInt32 from mscorlib as in
decimal value = 3.14m;
int n = Convert.ToInt32(value);
See MSDN. You can also use Decimal.ToInt32. Again, see MSDN. Finally, you can do a direct cast as in
decimal value = 3.14m;
int n = (int) value;
which uses the explicit cast operator. See MSDN.
You can't.
Well, of course you could, however an int (System.Int32) is not big enough to hold every possible decimal value.
That means if you cast a decimal that's larger than int.MaxValue you will overflow, and if the decimal is smaller than int.MinValue, it will underflow.
What happens when you under/overflow? One of two things. If your build is unchecked (i.e., the CLR doesn't care if you do), your application will continue after the value over/underflows, but the value in the int will not be what you expected. This can lead to intermittent bugs and may be hard to fix. You'll end up your application in an unknown state which may result in your application corrupting whatever important data its working on. Not good.
If your assembly is checked (properties->build->advanced->check for arithmetic overflow/underflow or the /checked compiler option), your code will throw an exception when an under/overflow occurs. This is probably better than not; however the default for assemblies is not to check for over/underflow.
The real question is "what are you trying to do?" Without knowing your requirements, nobody can tell you what you should do in this case, other than the obvious: DON'T DO IT.
If you specifically do NOT care, the answers here are valid. However, you should communicate your understanding that an overflow may occur and that it doesn't matter by wrapping your cast code in an unchecked block
unchecked
{
// do your conversions that may underflow/overflow here
}
That way people coming behind you understand you don't care, and if in the future someone changes your builds to /checked, your code won't break unexpectedly.
If all you want to do is drop the fractional portion of the number, leaving the integral part, you can use Math.Truncate.
decimal actual = 10.5M;
decimal expected = 10M;
Assert.AreEqual(expected, Math.Truncate(actual));
Videos
How to convert int to float in C?
Can we convert integer to float in C program automatically?
Does implicit conversion always work in int to float in C?
The fastest approach on all but the simplest (e.g. 8-bit) microcontrollers is to use division, but reduce the number of divisions by generating several digits at once.
You will find very highly optimized code in answers to my question here. Using it in C should be a trivial edit to eliminate std::string -- there are no C++ features used in the actual conversion. The core is
while(val>=100)
{
int pos = val % 100;
val /= 100;
*(short*)(c-1)=*(short*)(digit_pairs+2*pos); // or use memcpy
c-=2;
}
while(val>0)
{
*c--='0' + (val % 10);
val /= 10;
}
I also provided an optimized division-free code for 8-bit micros, similar to the idea shown in the code in the question, but without loops. It ends up with a lot of code like this:
if (val >= 80) {
ch |= '8';
val -= 80;
}
else if (val >= 40) {
ch |= '4';
val -= 40;
}
if (val >= 20) {
ch |= '2';
val -= 20;
}
if (val >= 10) {
ch |= '1';
val -= 10;
}
I believe integer division by a constant is as fast as doing a multiplication because the compiler optimizes integer division to integer multiplication for constant divisors. This is a heavy duty math trick performed by most optimizing compilers.
Use the strtoXXX() family of functions. If you need int, long or long long or their unsigned variants:
long l = strtol("1234567", NULL, 10);
long long ll = strtoll("1234567", NULL, 10);
unsigned long l = strtoul("1234567", NULL, 10);
If you need a float, double, or long double use this:
float f = strtof("3.1415927", NULL);
double d = strtod("3.1415927", NULL);
Manuals here and here.
Usually given a string:
char * myStr= "123";
the way to obtain it's value as an int is:
int value=atoi(myStr);
Some things important to notice:
the following include is necessary:
#include <stdlib.h>
and you must be sure that your string is a null terminated string otherwise atoi will crash you program.
You didn't gave us much information but if you're programming a microcontroller (I suspect that since you told us about a motor) you maybe won't want to use stdlib. In that case you might have use a costum function.
Please take a look at the code bellow:
int stringToInt(char* nrStr){
int nrChars=0;
while(nrStr[nrChars]!='\0'){
nrChars++;
}
int result=0;
int i=0;
while(nrStr[i]!='\0'){//while you dont get to the end of the string
int digit=nrStr[i]-48;//48 is zero ascii code
int exp=nrChars-i-1;
int add=digit*power(10,exp);
result+=add;
i++;
}
return result;
}
int power(int base, int exp){
int ret=1;
int i;
for(i=0;i<exp;i++){
ret*=base;
}
return ret;
}
This does not use any library functions and does the job. I've done it in 3 minutes and it may have some small error, it's not very efficient and does not verify possible errors, but in principle if you pass the strinToint function a well formed integer as a null terminated string it will output the correct value.
If you're using a library that does have some implementation of a power function do use it instead of the one I gave you since it is not efficient at all.
One last note: if you for some reason need to use it in other basis lets say octal basis, you have to chance the line:
int add=digit*power(10,exp);
to:
int add=digit*power(8,exp);
for hexadecimal this will not work, and implementation of such a function will be significantly different.
Hi! I'm learning to use operators and my handoobk used this program to explain them:
#include <stdio.h>
int main(void) {
/* Variables */
int a =100; b =2; c =25; d =4; result;
result = a - b; //substraction
printf ("a - b = %i\n", result);
}
But what if I want to operate result= c/b and then display it? How can I store the result of 25 / 2 in a variable that has been defined as an int type? Changing the variable type to floator doublemid program resulted in an error, and changing its type throughout the program displayed a 0 on all the operations.
You can't change local variable type:
// i is integer
int i = 10;
// and now i become decimal
decimal i = decimal.parse(i); // <- doesn't compile
But you can create another local variable:
int i = 10;
decimal d = i; // d == 10M
And .Net convert i into decimal for you (and so you have integer i == 10 and decimal d == 10m). There's an exotic possibility with dynamic typing
dynamic i = 15; // i is int
i = Convert.ToDecimal(i); // now i is decimal; "(decimal) i;" will do as well
but I doubt if you want it. If you insist on Parse() you should put an ugly
decimal d = decimal.Parse(i.ToString());
Since we parse from String representation only.
Edit:
But still the decimal value contains only integer i.e. 10 instead of 10.0
Math says that
10 == 10.0 == 10.00 == 10.000 == ...
thus if you want to change representation, you should use formatting:
Console.Write(d.ToString("F1")); // F1 - 1 digit after the decimal point
in case of decimal (not double) you can play a (dirty?) trick
decimal d = i + 0.0m;
Console.Write(d); // 10.0
decimal (or Decimal) defines an implicit conversion operator that allows you to simply write something like this:
int i = 10;
decimal d = i;