AlonH
AlonH

Reputation: 35

Format float to 4 decimal places without string conversion

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?

Upvotes: 0

Views: 1467

Answers (1)

John Mommers
John Mommers

Reputation: 140

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

Upvotes: 2

Related Questions