corwin
corwin

Reputation: 77

String formatting: float without integer part

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

Upvotes: 0

Views: 624

Answers (4)

corwin
corwin

Reputation: 77

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.

Upvotes: 0

Daweo
Daweo

Reputation: 36340

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.

Upvotes: 0

Olvin Roght
Olvin Roght

Reputation: 7812

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}')

Upvotes: 0

hiro protagonist
hiro protagonist

Reputation: 46839

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.

Upvotes: 3

Related Questions