Try out this modified version of numpy.trunc().

import numpy as np
def trunc(values, decs=0):
    return np.trunc(values*10**decs)/(10**decs)

Sadly, numpy.trunc function doesn't allow decimal truncation. Luckily, multiplying the argument and dividing it's result by a power of ten give the expected results.

vec = np.array([-4.79, -0.38, -0.001, 0.011, 0.4444, 2.34341232, 6.999])

trunc(vec, decs=2)

which returns:

>>> array([-4.79, -0.38, -0.  ,  0.01,  0.44,  2.34,  6.99])
Answer from Wolphyrus Imperius on Stack Overflow
🌐
W3Schools
w3schools.com › python › numpy › numpy_ufunc_rounding_decimals.asp
NumPy ufuncs - Rounding Decimals
Truncate elements of following array: import numpy as np arr = np.trunc([-3.1666, 3.6667]) print(arr) Try it Yourself » · Same example, using fix(): import numpy as np arr = np.fix([-3.1666, 3.6667]) print(arr) Try it Yourself » · The around() function increments preceding digit or decimal by 1 if >=5 else do nothing. E.g. round off to 1 decimal point, 3.16666 is 3.2 · Round off 3.1666 to 2 decimal places: import numpy as np arr = np.around(3.1666, 2) print(arr) Try it Yourself » ·
Discussions

how to limit or round a float to only two decimals without rounding up
You can try the solution here: https://stackoverflow.com/a/62435913 More on reddit.com
🌐 r/learnpython
12
5
March 8, 2024
python - generate random numbers truncated to 2 decimal places - Stack Overflow
I would like to generate uniformly distributed random numbers between 0 and 0.5, but truncated to 2 decimal places. without the truncation, I know this is done by import numpy as np rs = np.random. More on stackoverflow.com
🌐 stackoverflow.com
python - Limiting floats to two decimal points - Stack Overflow
I want a to be rounded to 13.95. I tried using round, but I get: >>> a 13.949999999999999 >>> round(a, 2) 13.949999999999999 Editor's note: For the analogous issue with the standard More on stackoverflow.com
🌐 stackoverflow.com
January 19, 2009
python - numpy float32 truncating decimal - Stack Overflow
I'm working on a school project that requires me to do some math on single-precision floating point numbers. I thought I would use the float32 format in numpy as python is really the only general p... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Codecademy
codecademy.com › docs › python:numpy › math methods › .trunc()
Python:NumPy | Math Methods | .trunc() | Codecademy
November 27, 2024 - The example demonstrates how .trunc() truncates the decimal values in a NumPy array: ... The above example also shows that .trunc() does not round but it simply removes the fractional part. The example below demonstrates how to selectively apply truncation using the where parameter, allowing truncation only for elements meeting a specified condition while leaving others unchanged: ... Original Numbers: [ 3.14 -2...
🌐
Medium
medium.com › @heyamit10 › understanding-numpy-truncate-c5e82bd519e9
Understanding numpy.truncate
March 6, 2025 - When it comes to numpy.truncate, simplicity is its superpower. Let’s jump straight into the code to see how it works in real scenarios. ... You might be thinking: “Wait, why didn’t -2.9 become -3?" That’s because truncate doesn’t care about rounding down or up—it just removes the decimal part, no questions asked.
🌐
NumPy
numpy.org › devdocs › reference › generated › numpy.trunc.html
numpy.trunc — NumPy v2.5.dev0 Manual
The truncated value of each element in x. This is a scalar if x is a scalar. ... Try it in your browser! >>> import numpy as np >>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0]) >>> np.trunc(a) array([-1., -1., -0., 0., 1., 1., 2.])
🌐
GeeksforGeeks
geeksforgeeks.org › python › numpy-trunc-python
numpy.trunc() in Python - GeeksforGeeks
March 8, 2024 - # Python program explaining # trunc() function import numpy as np in_array = [1.67, 4.5, 7, 9, 12] print ("Input array : \n", in_array) truncoff_values = np.trunc(in_array) print ("\nRounded values : \n", truncoff_values) in_array = [133.000, ...
Top answer
1 of 5
5

A float cannot be truncated (or rounded) to 2 decimal digits, because there are many values with 2 decimal digits that just cannot be represented exactly as an IEEE double.

If you really want what you say you want, you need to use a type with exact precision, like Decimal.

Of course there are downsides to doing that—the most obvious one for numpy users being that you will have to use dtype=object, with all of the compactness and performance implications.

But it's the only way to actually do what you asked for.

Most likely, what you actually want to do is either Joran Beasley's answer (leave them untruncated, and just round at print-out time) or something similar to Lauritz V. Thaulow's answer (get the closest approximation you can, then use explicit epsilon checks everywhere).

Alternatively, you can do implicitly fixed-point arithmetic, as David Heffernan suggests in a comment: Generate random integers between 0 and 50, keep them as integers within numpy, and just format them as fixed point decimals and/or convert to Decimal when necessary (e.g., for printing results). This gives you all of the advantages of Decimal without the costs… although it does open an obvious window to create new bugs by forgetting to shift 2 places somewhere.

2 of 5
3

decimals are not truncated to 2 decimal places ever ... however their string representation maybe

import numpy as np
rs = np.random.RandomState(123456)
set = rs.uniform(size=(50,1))*0.5

print ["%0.2d"%val for val in set]
Find elsewhere
Top answer
1 of 16
2331

You are running into the old problem with floating point numbers that not all numbers can be represented exactly. The command line is just showing you the full floating point form from memory.

With floating point representation, your rounded version is the same number. Since computers are binary, they store floating point numbers as an integer and then divide it by a power of two so 13.95 will be represented in a similar fashion to 125650429603636838/(2**53).

Double precision numbers have 53 bits (16 digits) of precision and regular floats have 24 bits (8 digits) of precision. The floating point type in Python uses double precision to store the values.

For example,

>>> 125650429603636838/(2**53)
13.949999999999999

>>> 234042163/(2**24)
13.949999988079071

>>> a = 13.946
>>> print(a)
13.946
>>> print("%.2f" % a)
13.95
>>> round(a,2)
13.949999999999999
>>> print("%.2f" % round(a, 2))
13.95
>>> print("{:.2f}".format(a))
13.95
>>> print("{:.2f}".format(round(a, 2)))
13.95
>>> print("{:.15f}".format(round(a, 2)))
13.949999999999999

If you are after only two decimal places (to display a currency value, for example), then you have a couple of better choices:

  1. Use integers and store values in cents, not dollars and then divide by 100 to convert to dollars.
  2. Or use a fixed point number like decimal.
2 of 16
838

There are new format specifications, String Format Specification Mini-Language:

You can do the same as:

"{:.2f}".format(13.949999999999999)

Note 1: the above returns a string. In order to get as float, simply wrap with float(...):

float("{:.2f}".format(13.949999999999999))

Note 2: wrapping with float() doesn't change anything:

>>> x = 13.949999999999999999
>>> x
13.95
>>> g = float("{:.2f}".format(x))
>>> g
13.95
>>> x == g
True
>>> h = round(x, 2)
>>> h
13.95
>>> x == h
True
🌐
TradingCode
tradingcode.net › python › math › truncate-decimals
Truncate numbers to decimal places in Python • TradingCode
The function then first multiplies that value with 100 (102). math.trunc() then truncates 1234.56 to a whole number. We then divide with 100 to get the result in 2 decimal places: 12.34.
🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.trunc.html
numpy.trunc — NumPy v2.4 Manual
The truncated value of each element in x. This is a scalar if x is a scalar. ... Try it in your browser! >>> import numpy as np >>> a = np.array([-1.7, -1.5, -0.2, 0.2, 1.5, 1.7, 2.0]) >>> np.trunc(a) array([-1., -1., -0., 0., 1., 1., 2.])
🌐
NumPy
numpy.org › doc › 2.1 › reference › generated › numpy.round.html
numpy.round — NumPy v2.1 Manual
The float printing routines use an accurate but much more computationally demanding algorithm to compute the number of digits after the decimal point. Alternatively, Python’s builtin round function uses a more accurate but slower algorithm for 64-bit floating point values: >>> round(56294995342131.5, 3) 56294995342131.5 >>> np.round(16.055, 2), round(16.055, 2) # equals 16.0549999999999997 (16.06, 16.05)
🌐
datagy
datagy.io › home › python posts › python strings › python: truncate a float (6 different ways)
Python: Truncate a Float (6 Different Ways) • datagy
April 14, 2024 - Numpy Tutorials · Learn Data Visualization · Python Seaborn · Python Matplotlib · About · All Posts · November 1, 2021April 14, 2024 · In this tutorial, you’ll learn how to use Python to truncate a float, to either no decimal places or a certain number of decimal places.
🌐
Codegive
codegive.com › blog › numpy_array_round_to_2_decimal_places.php
Numpy array round to 2 decimal places
For positive numbers, it's like floor; for negative numbers, it's like ceil. Similar to floor and ceil, you can use the multiplication/division trick: Example 4: Truncation-style Rounding to 2 Decimal Places · import numpy as np data = np.array([3.14159, 2.71828, 1.61803, -9.87654, -0.12345]) ...
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › python numpy round() array function
Python NumPy round() Array Function - Spark By {Examples}
March 27, 2024 - The round() function is a mathematical function that returns an array with rounded values of the input array. when you provide an input array with float values that you want to round the digits to our desired number of decimal places.
🌐
Real Python
realpython.com › python-rounding
How to Round Numbers in Python – Real Python
December 7, 2024 - You can use the built-in round() function, passing the number and the desired decimal places as arguments, for example, round(number, 2) to round to two decimal places. How do you apply different rounding strategies in Python?Show/Hide · You ...
🌐
Quora
quora.com › How-do-you-truncate-to-2-decimal-places-in-Python
How to truncate to 2 decimal places in Python - Quora
Method 1: Using “%” operator Syntax: float(“%.2f”%number) Explanation: The number 2 in above syntax represents the number of decimal places you want the value to round off too.
🌐
NumPy
numpy.org › doc › 2.2 › reference › generated › numpy.trunc.html
numpy.trunc — NumPy v2.2 Manual
At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized. ... For other keyword-only arguments, see the ufunc docs. ... The truncated value of each element in x.
🌐
TutorialsPoint
tutorialspoint.com › numpy › numpy_rounding_functions.htm
NumPy - Rounding Functions
Ceiled values: [4. 3. 2. 1.] The numpy.trunc() function truncates each element in the input array by removing the decimal part.