0

Given a float, I want to format it to display only the first 4 decimal places. (For example, given 12.345678 => I need 12.3456)

However, I'd like to do it in optimal complexity, so I'm aiming to avoid converting the float to string.

Is there any way to achieve this?

AlonH
  • 25
  • 4
  • 1
    If you're displaying it, you will need to convert it a string anyway. – Unmitigated Apr 30 '21 at 19:27
  • https://stackoverflow.com/a/20457284/14265469 – Yuri Khristich Apr 30 '21 at 19:28
  • 1
    You sure you want to truncate `12.345678` to `12.3456` instead of rounding to `12.3457`? – khelwood Apr 30 '21 at 19:29
  • Please repeat [on topic](https://stackoverflow.com/help/on-topic) and [how to ask](https://stackoverflow.com/help/how-to-ask) from the [intro tour](https://stackoverflow.com/tour). “Show me how to solve this coding problem” is not a Stack Overflow issue. We expect you to make an honest attempt, and *then* ask a *specific* question about your algorithm or technique. Stack Overflow is not intended to replace existing documentation and tutorials. You need to look up how to format, round, truncate, ... float output. We expect you to include that searching in your posted question. – Prune Apr 30 '21 at 19:35

1 Answers1

2

Use floor (numpy) to just display the first 4 decimals, however not rounding:

np.floor(12.345678*10000)/10000

Out:

12.3456

Use round() just to round down to 4 decimal places:

round(12.345678,4)

Out: 12.3457

John Mommers
  • 140
  • 7