Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer to float

Tags:

This code works:

posToXY :: Float -> Float -> Integer posToXY a b = do         let y = a / b         round y 

But this doesn't work:

posToXY :: Integer -> Integer -> Integer posToXY a b = do         let y = a / b         round y 

I understand that operation '/' doesn't define for Integer type, but I don't know how to fix code to work with Integer parameters.

like image 718
ceth Avatar asked Oct 19 '10 12:10

ceth


People also ask

Can integer convert to float?

To convert an integer data type to float you can wrap the integer with float64() or float32. Explanation: Firstly we declare a variable x of type int64 with a value of 5. Then we wrap x with float64(), which converts the integer 5 to float value of 5.00.

Can I use %d for float?

So, you can see here that %d is used for integers, %f for floats and %c for characters.

Can you convert int to float in C?

Just Make the number variable int to float. int total=0, number=0; float percentage=0.0; percentage=((float)number/total)*100; printf("%. 2f", percentage);

How do you float an integer in Python?

Python also has a built-in function to convert floats to integers: int() . In this case, 390.8 will be converted to 390 . When converting floats to integers with the int() function, Python cuts off the decimal and remaining numbers of a float to create an integer.


1 Answers

If you want to perform fractional division, you can convert from any Integral type using fromIntegral, or fromInteger to convert only from Integer specifically.

There are similar functions relating to other numeric type classes: toRational, fromRational, realToFrac, etc. And of course you can convert fractional types back to integral types using round, floor, ceiling, or such.

And finally, on the off chance that you actually wanted integer division, instead of fractional division with rounding afterwards, there's the div and quot functions (depending on what truncation behavior you want).

Also, you probably should write your function as something like posToXY a b = round $ a / b. The unnecessary do and multiple lines makes it harder to read.

like image 62
C. A. McCann Avatar answered Oct 23 '22 02:10

C. A. McCann