Why are floating point numbers inaccurate?

In most programming languages, floating point numbers are represented a lot like scientific notation: with an exponent and a mantissa (also called the significand). A very simple number, say 9.2, is actually this fraction: 5179139571476070 * 2 -49 Where the exponent is -49 and the mantissa is 5179139571476070. The reason it is impossible to represent … Read more

Format / Suppress Scientific Notation from Pandas Aggregation Results

Granted, the answer I linked in the comments is not very helpful. You can specify your own string converter like so. In [25]: pd.set_option(‘display.float_format’, lambda x: ‘%.3f’ % x) In [28]: Series(np.random.randn(3))*1000000000 Out[28]: 0 -757322420.605 1 -1436160588.997 2 -1235116117.064 dtype: float64 I’m not sure if that’s the preferred way to do this, but it works. … Read more

round() for float in C++

Editor’s Note: The following answer provides a simplistic solution that contains several implementation flaws (see Shafik Yaghmour’s answer for a full explanation). Note that C++11 includes std::round, std::lround, and std::llround as builtins already. There’s no round() in the C++98 standard library. You can write one yourself though. The following is an implementation of round-half-up: double … Read more

Can anyone explain this strange behavior with signed floats in C#?

The bug is in the following two lines of System.ValueType: (I stepped into the reference source) if (CanCompareBits(this)) return FastEqualsCheck(thisObj, obj); (Both methods are [MethodImpl(MethodImplOptions.InternalCall)]) When all of the fields are 8 bytes wide, CanCompareBits mistakenly returns true, resulting in a bitwise comparison of two different, but semantically identical, values. When at least one field … Read more

How do I restrict a float value to only two places after the decimal point in C?

If you just want to round the number for output purposes, then the “%.2f” format string is indeed the correct answer. However, if you actually want to round the floating point value for further computation, something like the following works: #include <math.h> float val = 37.777779; float rounded_down = floorf(val * 100) / 100; /* … Read more

Add floating point value to android resources/values

There is a solution: <resources> <item name=”text_line_spacing” format=”float” type=”dimen”>1.0</item> </resources> In this way, your float number will be under @dimen. Notice that you can use other “format” and/or “type” modifiers, where format stands for: Format = enclosing data type: float boolean fraction integer … and type stands for: Type = resource type (referenced with R.XXXXX.name): … Read more