Formatting Floating-Point Numbers with numpy.format_float_positional()


  • Trimming
    The function allows you to control how trailing zeros and the decimal point are handled after rounding. Here are the options for the trim parameter:
    • 'k': This keeps trailing zeros and the decimal point (no trimming).
    • '. ': This trims all trailing zeros but leaves the decimal point.
    • '0': This trims all trailing zeros except for the zero before the decimal point, effectively removing the decimal point if no significant digits follow it.
    • '-': This trims both trailing zeros and the decimal point.
  • Rounding Control
    You can specify the desired number of decimal places to be displayed using the precision parameter. By default, all the significant digits are included.
  • Positional Notation
    The output string is formatted in standard decimal form, without resorting to scientific notation.
  • Formatting
    It transforms a floating-point scalar (a single floating-point number) into a human-readable string representation.

In essence, it offers a customizable way to format floating-point numbers for output purposes.

import numpy as np

# Sample float number
float_number = 123.456789

# Formatting with default precision (all significant digits)
print(np.format_float_positional(float_number))

# Formatting with 2 decimal places
print(np.format_float_positional(float_number, precision=2))

# Formatting with 4 decimal places, keeping trailing zeros
print(np.format_float_positional(float_number, precision=4, trim='k'))

# Formatting to remove trailing zeros but keep the decimal point
print(np.format_float_positional(float_number, precision=4, trim='. '))

This code will output the following:

123.456789
123.46
123.45680000
123.4568


Specifying Unique Suffixes for Exponents (optional)

By default, the function uses the letter 'e' to denote exponents. You can set the unique parameter to False to suppress the exponent altogether (if the number remains within the positional format) or set a custom string using unique=my_suffix (like 'E' or 'x10^').

import numpy as np

# Large number with default exponent ('e')
large_num = 1.234e10
print(np.format_float_positional(large_num))

# Suppressing exponent (if possible)
print(np.format_float_positional(large_num, unique=False))

# Custom exponent suffix
print(np.format_float_positional(large_num, unique='E'))

Padding the Output String (optional)

Use the pad_left and pad_right arguments to add spaces or any other characters for padding the output string to a desired length.

import numpy as np

# Float with padding on both sides (using spaces)
value = 3.14159
print(np.format_float_positional(value, precision=4, pad_left=5, pad_right=10))

# Padding with specific character (using '-')
print(np.format_float_positional(value, precision=4, pad_left=3, pad_right=7, pad_char='-'))

Formatting Very Small or Large Numbers

The function handles numbers that might overflow the standard positional format. Numbers exceeding this limit are automatically converted to scientific notation.

import numpy as np

# Very small number (trims trailing zeros)
tiny_value = 1.234e-10
print(np.format_float_positional(tiny_value, trim='-'))

# Very large number (scientific notation)
huge_value = 1.234e20
print(np.format_float_positional(huge_value))


  1. f-strings (Python 3.6+)

f-strings provide a concise and readable way to format strings with variables. You can embed expressions directly into strings using curly braces {}.

import numpy as np

value = 3.14159

# Formatting with 2 decimal places
formatted_string = f"Value: {value:.2f}"
print(formatted_string)
  1. str.format() method

This built-in string formatting method offers flexibility and control over formatting options. You can use format specifiers within curly braces to define how the variable should be displayed.

import numpy as np

value = 3.14159

# Formatting with 4 decimal places, keeping trailing zeros
formatted_string = "Value: {:.4f}".format(value)
print(formatted_string)

# Formatting with padding (10 spaces to the right)
formatted_string = "Value: {:<10.2f}".format(value)
print(formatted_string)
  1. '{:.nf}'.format(value)

This is a shorthand for str.format() using the format specifier '.nf'. The 'n' represents the number of significant digits, and 'f' denotes fixed-point notation.

import numpy as np

value = 3.14159

# Formatting with 3 significant digits
formatted_string = '{:.3f}'.format(value)
print(formatted_string)
  1. '{:E}'.format(value)

This shorthand uses the format specifier 'E' to represent the number in scientific notation.

import numpy as np

value = 1.234e10

# Formatting in scientific notation
formatted_string = '{:E}'.format(value)
print(formatted_string)
  1. pandas.to_string() (if using pandas)

If you're working with pandas DataFrames or Series, you can leverage the to_string() method with formatting options.

import pandas as pd

data = {'Values': [3.14159, 123.456]}
df = pd.DataFrame(data)

# Formatting with 2 decimal places for all values in the 'Values' column
formatted_string = df.to_string(format_float="{:.2f}".format)
print(formatted_string)