-3

How can I limit the decimal places of a 'float' in python without rounding the number?

For example:

a = 1.45698946
>>
Limit_a = 1.45698

And not:

1.45699
Artemis
  • 2,553
  • 7
  • 21
  • 36
Mohammaf
  • 9
  • 2
  • 1
    Welcome to your first question on StackOverflow. You need to make your question clear enough to answer. Are you asking how to *round down* to a given number of decimal places--5 in your example? If so, is it round toward zero or round toward negative infinity (those are different for negative numbers)? Do you want the result as a float value or a string value? If a float value, how should we handle the fact that float values are rarely exact? – Rory Daulton Jul 07 '18 at 22:40
  • thank you very much. the second comment is what I need – Mohammaf Jul 07 '18 at 22:53
  • What is "the second comment"? Do you mean the second *answer*? You should be aware that the order of answers changes, depending on several factors, and readers will not be aware which of the two current answers is the second one in your browser right now. – Rory Daulton Jul 07 '18 at 22:55
  • I looked at a few of the other threads on this question and many use string conversions which I wouldn't recommend. The best solutions use some variation of round(numToTruncate-.5). Here is my variation using round and retaining your five decimal places: round(n - (1/10**5),5) where n = 1.45698946 and '5' is number of decimal places to retain. – LAS Jul 07 '18 at 23:20

2 Answers2

0

This is long winded, but will give you the constituent parts to do something more elegant.

decimalPlaces = 5
val = 1.45698946
mod = 10 ** decimalPlaces
truncated = float(int(val * dps)) / dps

For values with less than 5 decimal places, you get the original value.

brindy
  • 4,585
  • 2
  • 24
  • 27
0

To avoid float precision errors I recommend using decimal module:

from decimal import Decimal

a = 1.45698946
limit_a = str(int(a)) + str(Decimal(str(a)) % 1)[1:7] 
print(float(limit_a))

Output is:

1.45698
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91