GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • The decimal module
  • String formatting in Python
  • Home
  • Basic Answers
  • References
  • xkcd
  • Binary Fractions
  • Floating-Point
  • Exact Types
  • On Using Integers
  • Rounding
  • Comparison
  • Propagation
  • C#

This view

  • Original page
  • New address

GeezerVison is showing floating-point-gui.de — The Floating-Point Guide - Floating-point cheat sheet for Python

Floating-point cheat sheet for Python

Floating-Point Types

Almost all platforms map Python floats to IEEE 754 double precision.

	f = 0.1 

Decimal Types

Python has an arbitrary-precision decimal type named Decimal in the decimal module, which also allows to choose the rounding mode.

	a = Decimal('0.1')
	b = Decimal('0.2')
	c = a + b # returns a Decimal representing exactly 0.3

How to Round

To get a string:

	"%.2f" % 1.2399 # returns "1.24"
	"%.3f" % 1.2399 # returns "1.240"
	"%.2f" % 1.2 # returns "1.20"

To print to standard output:

	print("%.2f" % 1.2399) # just use print and string formatting

Specific rounding modes and other parameters can be defined in a Context object:

	getcontext().prec = 7

Resources

  • Floating Point Arithmetic: Issues and Limitations
  • The decimal module
    • Context objects
  • String formatting in Python

© Published at floating-point-gui.de under the Creative Commons Attribution License (BY)

The Floating-Point Guide

  • Home
  • Basic Answers
  • References
  • xkcd

Number Formats

  • Binary Fractions
  • Floating-Point
  • Exact Types
  • On Using Integers

Errors

  • Rounding
  • Comparison
  • Propagation

Language
cheat sheets

  • C#
  • Java
  • JavaScript
  • Perl
  • PHP
  • Python
  • Ruby
  • Rust
  • SQL
Fork me on GitHub
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.