Chris
Chris

Reputation: 22247

How to calculate a value to a certain number of decimal places?

Using numpy or python's standard library, either or. How can I take a value with several decimal places and truncate it to 4 decimal places? I only want to compare floating point numbers to their first 4 decimal points.

Upvotes: 2

Views: 1399

Answers (4)

John La Rooy
John La Rooy

Reputation: 304137

>>> round(1.2345678,4) == round(1.2345999,4)
True

Upvotes: 2

John Machin
John Machin

Reputation: 82924

round(a_float, 4)

>>> help(round)
Help on built-in function round in module __builtin__:

round(...)
    round(number[, ndigits]) -> floating point number

    Round a number to a given precision in decimal digits (default 0 digits).
    This always returns a floating point number.  Precision may be negative.

>>>

Upvotes: 6

Goran Rakic
Goran Rakic

Reputation: 1799

If you want to compare two floats, you can compare on abs(a-b) < epsilon where epsilon is your precision requirement.

Upvotes: 3

ghostdog74
ghostdog74

Reputation: 342333

you can use decimal module, especially the part on getcontext().prec

Upvotes: 1

Related Questions