Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
So I've got a project I'm working on. This is the only error I have:
Cannot implicitly convert type 'float' to 'int'.
I understand somewhat what that means. I just need help converting my float to int.
This is just an example of one of the floats:
float key = 0.5f;
int key = 53;
Here's the specific code section:
// price in scrap, e.g. 29 / 9 = 3.33 ref
static int BuyPricePerTOD = 21;
// price in scrap, e.g. 31 / 9 = 3.55 ref
static float SellPricePerTOD = BuyPricePerTOD + 0.5F;
static int BuyPricePerKey = 53;
static float SellPricePerKey = BuyPricePerKey + 0.5F;
static int TimerInterval = 170000;
static int InviteTimerInterval = 2000;
int UserWeapAdded,UserScrapAdded,UserRecAdded,UserRefAdded,
UserKeysAdded,UserTODAdded,BotTODsAdded,BotKeysAdded,
BotScrapAdded,BotRecAdded,BotRefAdded,InventoryMetal,
InventoryScrap,InventoryRec,InventoryRef,InventoryKeys,
InventoryTOD,PreviousTODs,PreviousKeys,WhileLoop,InvalidItem = 0;
float UserMetalAdded, BotMetalAdded, OverpayNumKeys,
OverpayNumTOD, ExcessInScrapKey, ExcessInScrapTOD = 0.0F;
double ExcessRefinedKey, ExcessRefinedTOD = 0.0;
Firstly, there are integers and floating-point numbers. Integers are always whole numbers, such as 0, 1, -32, 42 and 1337. On the other hand, floating-point numbers can have a fractional part: 0, 1, -32.1, 42.7 and 123.456788 are all valid floating-point numbers.
When converting between integers (int) and floating-point (float) numbers, you can do this:
int someInt = 42;
float someFloat = someInt; // 42.0f
But you can't do this:
float someFloat = 42.7f;
int someInt = someFloat; // ?
The reason the first conversion is possible, is that converting the integer number (int) to a floating-point number (float) does not change the number. It is a safe conversion, and therefore can be done implicitly.
The reason the second conversion is not allowed, is that converting the floating-point number (which may have a fractional part) to an integer number (that never has a fractional part) must drop the fractional part of the number, i.e. it becomes a different number. This is not safe, and can therefore only be done explicitly.
To explicitly convert one type of number to another, you use a cast. That's the parentheses before the number with the type of the number that you want to convert it to.
float someFloat = 42.7f;
int someInt = (int)someFloat; // 42
Note that the fractional part of the floating-point number was dropped. It's as if it has been rounded towards zero. If you want to round the floating-point number to the nearest whole number, use the Math.Round method.
float someFloat = 42.7f;
int someInt = (int)Math.Round(someFloat); // 43
Try this :
int numInt = (int)Math.Ceiling(numFloat);
msdn documentation
You may want Math.Round() or Math.Floor() by the way.
Example :
float numFloat = 1.5f;
int testCeiling = (int)Math.Ceiling(numFloat);
int testFloor = (int)Math.Floor(numFloat);
int testRound = (int)Math.Round(numFloat);
Console.WriteLine("testCeiling = {0}", testCeiling.ToString());
Console.WriteLine("testFloor = {0}", testFloor.ToString());
Console.WriteLine("testRound= {0}", testRound.ToString());
output :
testCeiling = 2
testFloor = 1
testRound= 2
Related
Float f = 123456789F
Output of float
Float = 1.234568E+08
Output shown while converting to
Int = 123456792
Long = 123456792
D = 123456792
String = 1.234568E+08
Float is number with a decimal point from -3.402823e38 to 3.402823e38
Int is an integer from -2,147,483,648 to 2,147,483,647
Long is like int, but it has more space to use (from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807)
String is stored like a text, not the actuall number.
I have an interesting problem, I need to convert an int to a decimal.
So for example given:
int number = 2423;
decimal convertedNumber = Int2Dec(number,2);
// decimal should equal 24.23
decimal convertedNumber2 = Int2Dec(number,3);
// decimal should equal 2.423
I have played around, and this function works, I just hate that I have to create a string and convert it to a decimal, it doesn't seem very efficient:
decimal IntToDecConverter(int number, int precision)
{
decimal percisionNumber = Convert.ToDecimal("1".PadRight(precision+1,'0'));
return Convert.ToDecimal(number / percisionNumber);
}
Since you are trying to make the number smaller couldn't you just divide by 10 (1 decimal place), 100 (2 decimal places), 1000 (3 decimal places), etc.
Notice the pattern yet? As we increase the digits to the right of the decimal place we also increase the initial value being divided (10 for 1 digit after the decimal place, 100 for 2 digits after the decimal place, etc.) by ten times that.
So the pattern signifies we are dealing with a power of 10 (Math.Pow(10, x)).
Given an input (number of decimal places) make the conversion based on that.
Example:
int x = 1956;
int powBy=3;
decimal d = x/(decimal)Math.Pow(10.00, powBy);
//from 1956 to 1.956 based on powBy
With that being said, wrap it into a function:
decimal IntToDec(int x, int powBy)
{
return x/(decimal)Math.Pow(10.00, powBy);
}
Call it like so:
decimal d = IntToDec(1956, 3);
Going the opposite direction
You could also do the opposite if someone stated they wanted to take a decimal like 19.56 and convert it to an int. You'd still use the Pow mechanism but instead of dividing you would multiply.
double d=19.56;
int powBy=2;
double n = d*Math.Pow(10, powBy);
You can try create decimal explictly with the constructor which has been specially designed for this:
public static decimal IntToDecConverter(int number, int precision) {
return new decimal(Math.Abs(number), 0, 0, number < 0, (byte)precision);
}
E.g.
Console.WriteLine(IntToDecConverter(2423, 2));
Console.WriteLine(IntToDecConverter(1956, 3));
Outcome:
24.23
1.956
Moving the decimal point like that is just a function of multiplying/dividing by a power of 10.
So this function would work:
decimal IntToDecConverter(int number, int precision)
{
// -1 flips the number so its a fraction; same as dividing below
decimal factor = (decimal)Math.Pow(10, -1*precision)
return number * factor;
}
number/percisionNumber will give you an integer which you then convert to decimal.
Try...
return Convert.ToDecimal(number) / percisionNumber;
Convert your method like as below
public static decimal IntToDecConverter(int number, int precision)
{
return = number / ((decimal)(Math.Pow(10, precision)));
}
Check the live fiddle here.
Here is the code which made me post this question.
// int integer;
// int fraction;
// double arg = 110.1;
this.integer = (int)(arg);
this.fraction = (int)((arg - this.integer) * 100);
The variable integer is getting 110. That's OK.
The variable fraction is getting 9, however I am expecting 10.
What is wrong?
Update
It seems I have discovered that the source of the problem is subtraction
arg - this.integer
Its result is 0.099999999999994316.
Now I am wondering how I should correctly subtract so that the result was 0.1.
You have this:
fraction = (int)((110.1 - 110) * 100);
The inner part ((110.1 - 110) * 100), will be 9.999999
When you cast it to int, it will be round off to 9
This is because of "floating point" (see here) limitations:
Computers always need some way of representing data, and ultimately
those representations will always boil down to binary (0s and 1s).
Integers are easy to represent, but non-integers are a bit more
tricky. Consider the following var:
double x = 0.1d;
The variable x will actually store the closest available double to
that value. When you understand this, it becomes obvious why some
calculations seem to be "wrong".
If you were asked to add a third to a third, but could only use 3
decimal places, you'd get the "wrong" answer: the closest you could
get to a third is 0.333, and adding two of those together gives 0.666,
rather than 0.667 (which is closer to the exact value of two thirds).
Update:
In financial applications or where the numbers are so important to be exact, you can use decimal data type:
(int)((110.1m - 110) * 100) //will be 10 (m is decimal symbol)
or:
decimal arg = 110.1m;
int integer = (int)(arg); //110
decimal fraction = (int)((arg - integer) * 100); //will be 10
It is because you are using double, precision gets rounded, if you want it to be 10 use decimal type:
check the following:
int integer;
int fraction;
decimal arg = 110.1M;
integer = (int)(arg);
decimal diff = arg - integer;
decimal multiply = diff * 100;
fraction = (int)multiply;//output will be 10 as you expect
This question already has answers here:
How can I divide two integers to get a double?
(9 answers)
Closed 7 years ago.
I'm trying to calculate the area of a sector but when I divide angleParse by 360 and times it by radiusParse, I will sometimes receive a output of 0.
What happens and where do I need to fix it? (Sorry, if this is a weird question but I started learning C# yesterday, also I just started using StackOverflow today)
Frostbyte
static void AoaSc()
{
Console.WriteLine("Enter the radius of the circle in centimetres.");
string radius = Console.ReadLine();
int radiusParse;
Int32.TryParse(radius, out radiusParse);
Console.WriteLine("Enter the angle of the sector.");
string sectorAngle = Console.ReadLine();
int angleParse;
Int32.TryParse(sectorAngle, out angleParse);
double area = radiusParse * angleParse / 360;
Console.WriteLine("The area of the sector is: " + area + "cm²");
Console.ReadLine();
}
You've encountered integer division. If a and b are int, then a / b is also an int, where the non-integer part has been truncated (i.e. everything following the decimal point has been cut off).
If you want the "true" result, one or more of the operands in your division needs to be a floating point. Either of the following will work:
radiusParse * (double)angleParse / 360;
radiusParse * angleParse / 360.0;
Note that it's not sufficient to cast radiusParse to double, because the / operator has higher precedence than * (so the integer division happens first).
Finally, also note that decimal in .NET is its own type, and is distinct from float and double.
I think if you divide it by 360.0 it will work.
Alternatively declare a variable of type decimal and set this to 360.
private decimal degreesInCirle = 360;
// Other code removed...
double area = radiusParse * angleParse / degreesInCirle;
I have a method that tests a value is within the range allowed on fields. If it is outside the range returns null and if inside returns the value.
internal float? ExtractMoneyInRangeAndPrecision(string fieldValue, string fieldName, float min, float max, int scale, int lineNumber)
{
float returnValue;
//Check whether valid float if
if (float.TryParse(fieldValue, out returnValue))
{
//Check whether in range
if (returnValue >= min && returnValue <= max)
{
int decPosition = 0;
decPosition = fieldValue.IndexOf('.');
if (
(decPosition == -1) ||
((decPosition != -1) && (fieldValue.Substring(decPosition, fieldValue.Length - decPosition).Length -1 <= scale))
)
{
return returnValue;
}
}
}
return null;
}
Here is my unit test:
[TestMethod()]
[DeploymentItem("ImporterEngine.dll")]
public void ExtractMoneyInRangeAndPrecisionTest_OutsideRange()
{
MockSyntaxValidator target = new MockSyntaxValidator("", 0);
string fieldValue = "1000000";
string fieldName = "";
float min = 1;
float max = 999999.99f;
int scale = 2;
int lineNumber = 0;
float? Int16RangeReturned;
Int16RangeReturned = target.ExtractMoneyInRangeAndPrecision(fieldValue, fieldName, min, max, scale, lineNumber);
Assert.IsNull(Int16RangeReturned);
}
As you can see the max is 999999.99 but when the method takes it in it changes it to 1,000,000
Why is this?
http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems
In short, because of the way floating-point numbers represent real numbers, the number you assign to a float is not always the number you get back out. The value you specify is converted to the nearest value that can be represented in scientific notation with a magnitude determined by a base of 2.
In the case of 999999.99, the nearest number that can be represented as a float with the same number of sig figs is 7.6293945 * 217 = 999999.99504, which when rounded to the same sig figs is 1,000,000.00. This may not be the EXACT case, but error like this is inherent in the use of floats.
Do not use floating-point types in situations where the accuracy of the number at a given level of precision is required. Instead, use the decimal type, which will retain the precision of values entered.
Not every string of digits can be converted to a float. Without checking, I would say that 999999.99 is one such number. A decimal would solve this.
The float type doesn't have enough precision to do what you want to do. I would recommend using the decimal type. Floats can be accurate to 7 decimal digits at most, and you're using 8 here. Decimal can have up to 28 digits, which is more than enough for any amount. Moreover, unlike float, the value the compiler uses and the value you write will always be the same.
Here's the long explanation:
Floats (single-precision floating-point numbers) are stored as an integer times a power of two, where the integer is in a certain range (between 2^23 and 2^24).
When you write a decimal number in your code, the compiler interprets this as the number in this form that is closest to the number you wrote. Sometimes the match is exact (99999.75). In other cases, your number needs to be rounded to the closest floating-point number. This is what happened here:
99999.99 = 2^19 * 1.907348613739013671875
= 2^19 * 2^-23 * (2^23 * 1.907348613739013671875)
= 2^-4 * 15999999.84
The closest integer to 15999999.84 is 16000000, so the rounded value is
(float)99999.99 = 2^-4 * 16000000
= 1000000
The big advantage of the decimal type is that is represented as a 96 bit integer times a power of 10, so decimal numbers with up to 28 digits can be represented exactly, without any rounding. What you see is what you get.
The biggest disadvantage of decimal is that it is significantly slower, but in a situation like this where you're converting strings to numbers, this is not a factor.
Floating-point types (as defined in C#) are approximate. For precision you should always use decimal.
From MSDN:
The decimal keyword indicates a 128-bit data type. Compared to floating-point types, the decimal type has more precision and a smaller range, which makes it appropriate for financial and monetary calculations. The approximate range and precision for the decimal type are shown in the following table.
http://msdn.microsoft.com/en-us/library/364x0z75.aspx
There seems to be some dispute about what qualifies as a floating-point type in C#. While decimal does qualify as a floating-point type by actual definition, it is not defined as such according to the MSDN specification.
http://msdn.microsoft.com/en-us/library/9ahet949.aspx