Getting the decimal part of a double in Swift

You can use truncatingRemainder and 1 as the divider. Returns the remainder of this value divided by the given value using truncating division. Apple doc Example: let myDouble1: Double = 12.25 let myDouble2: Double = 12.5 let myDouble3: Double = 12.75 let remainder1 = myDouble1.truncatingRemainder(dividingBy: 1) let remainder2 = myDouble2.truncatingRemainder(dividingBy: 1) let remainder3 = myDouble3.truncatingRemainder(dividingBy: … Read more

Python float – str – float weirdness

str(0.47000000000000003) give ‘0.47’ and float(‘0.47’) can be 0.46999999999999997. This is due to the way floating point number are represented (see this wikipedia article) Note: float(repr(0.47000000000000003)) or eval(repr(0.47000000000000003)) will give you the expected result, but you should use Decimal if you need precision.

Why does the floating-point value of 4*0.1 look nice in Python 3 but 3*0.1 doesn’t?

The simple answer is because 3*0.1 != 0.3 due to quantization (roundoff) error (whereas 4*0.1 == 0.4 because multiplying by a power of two is usually an “exact” operation). Python tries to find the shortest string that would round to the desired value, so it can display 4*0.1 as 0.4 as these are equal, but … Read more

Truncate (not round off) decimal numbers in javascript

Dogbert’s answer is good, but if your code might have to deal with negative numbers, Math.floor by itself may give unexpected results. E.g. Math.floor(4.3) = 4, but Math.floor(-4.3) = -5 Use a helper function like this one instead to get consistent results: truncateDecimals = function (number) { return Math[number < 0 ? ‘ceil’ : ‘floor’](number); … Read more

C++ floating point precision [duplicate]

To get the correct results, don’t set precision greater than available for this numeric type: #include <iostream> #include <limits> int main() { double a = 0.3; std::cout.precision(std::numeric_limits<double>::digits10); std::cout << a << std::endl; double b = 0; for (char i = 1; i <= 50; i++) { b = b + a; }; std::cout.precision(std::numeric_limits<double>::digits10); std::cout << … Read more