Split decimal variable into integral and fraction parts
decimal fraction = (decimal)2.78; int iPart = (int)fraction; decimal dPart = fraction % 1.0m;
decimal fraction = (decimal)2.78; int iPart = (int)fraction; decimal dPart = fraction % 1.0m;
Since no one has mentioned it yet there is a quick and dirty solution: var decimal = eval(fraction); Which has the perks of correctly evaluating all sorts of mathematical strings. eval(“3/2”) // 1.5 eval(“6”) // 6 eval(“6.5/.5”) // 13, works with decimals (floats) eval(“12 + 3”) // 15, you can add subtract and multiply too … Read more
Historical note: the comment thread below may refer to first and second implementations. I swapped the order in September 2017 since leading with a buggy implementation caused confusion. If you want something that maps “0.1e-100” to 101, then you can try something like function decimalPlaces(n) { // Make sure it is a number and use … Read more
The fractions module can do that >>> from fractions import Fraction >>> Fraction(98, 42) Fraction(7, 3) There’s a recipe over here for a numpy gcd. Which you could then use to divide your fraction >>> def numpy_gcd(a, b): … a, b = np.broadcast_arrays(a, b) … a = a.copy() … b = b.copy() … pos = … Read more
// Reduce a fraction by finding the Greatest Common Divisor and dividing by it. function reduce(numerator,denominator){ var gcd = function gcd(a,b){ return b ? gcd(b, a%b) : a; }; gcd = gcd(numerator,denominator); return [numerator/gcd, denominator/gcd]; } reduce(2,4); // [1,2] reduce(13427,3413358); // [463,117702]
Try the following: 1<sup>1</sup>⁄<sub>2</sub> This displays as: 11⁄2
It just so happens that I wrote a BigFraction class not too long ago, for Project Euler problems. It keeps a BigInteger numerator and denominator, so it’ll never overflow. But it’ll be a tad slow for a lot of operations that you know will never overflow.. anyway, use it if you want it. I’ve been … Read more
You have two options: Use float.as_integer_ratio(): >>> (0.25).as_integer_ratio() (1, 4) (as of Python 3.6, you can do the same with a decimal.Decimal() object.) Use the fractions.Fraction() type: >>> from fractions import Fraction >>> Fraction(0.25) Fraction(1, 4) The latter has a very helpful str() conversion: >>> str(Fraction(0.25)) ‘1/4’ >>> print Fraction(0.25) 1/4 Because floating point values … Read more
You can either use: [x / 10.0 for x in range(5, 50, 15)] or use lambda / map: map(lambda x: x/10.0, range(5, 50, 15))