0

I need to print a value into log file. My value is a float in range 0-1. The value needs to be formatted as 4 decimal digits, without integer part. So 0.42 will be printed as 4200, and with some text before.

This is my current approach:

value = 0.42
print('my value is ' + f'{value:.4f}'[2:])

It somehow doesn't look very nice, so the question is: can I use float formatting in a way that I could avoid concatenating two string, something like:

print(f'my value is {value:-1.4f}') # this looks nicer but doesn't do what I want
1
  • A bit offtopic: why do you want to do that? Your original code looks nice to me. Commented May 10, 2019 at 10:58

4 Answers 4

3

this might work:

value = 0.42
print('my value is ' + f'{int(10000*value):4d}')
# my value is 4200

where i convert your float to an int first and the use integer formatting :4d.

or you may want to round first.

Sign up to request clarification or add additional context in comments.

Comments

0

Your code is pretty good, you can leave it like it is. There's also other way, but I'm not sure that it's nice.

value = 0.42
print(f'my value is {str(value)[2:]:0<4}')

Comments

0

There is nothing wrong with contentation of strs to get argument for print, however if you are not allowed to do so, you can use following workaround:

value = 0.42
print('my value is',f'{value:.4f}'[2:])

Output:

my value is 4200

Note that I removed last space from my values is as print by default adds spaces between arguments it receive.

Comments

0

Thank you for your suggestions. To sum everything up, what I didn't like in my original solution is that its not clearly visible what its doing at the first glance. I think slightly modified version posted by hiro protagonist is better:

print(f'my value is {int(10000*value):04d}')

There is no need to split string + I need to add add '04d' to print leading zeros in case the number is smaller.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.