简体   繁体   English

Python3.x:格式浮动到2位,限制为3个小数位

[英]Python3.x: Format Float to 2 Digits, Limit to 3 Decimal places

I have seen many questions about formatting floats and limiting decimal places, but I have not seen both done at once. 我已经看到很多关于格式化floats和限制小数位的问题,但我还没有看到两者同时完成。 I want the values for my variable seconds to always be represented as SS.mmm. 我希望我的变量seconds的值始终表示为SS.mmm。

I have 我有

t = int(input('time?: '))
seconds = (t / 1000) % 60
minutes = (t // (1000 * 60)) % 60
hours = (t // (1000 * 60 * 60)) % 24

I want to print hours , minutes , and seconds so that it will always follow HH:MM:SS.mmm 我想打印hoursminutesseconds以便它始终跟随HH:MM:SS.mmm

My attempt: 我的尝试:

print('{}:{}:{}'.format("%02d" % hours, "%02d" % minutes, ("%.3f" % seconds).zfill(2)))

I end up getting HH:MM:S.mmm sometimes. 我最终得到了HH:MM:有时候是S.mmm。 I need there to be two seconds digits even if there is a leading zero. 即使有一个前导零,我还需要两秒钟的数字。

You should be able to do the following with .format() : 您应该能够使用.format()执行以下.format()

print('{:0>2d}:{:0>2d}:{:06.3f}'.format(hours,minutes,seconds))

In particular, 0>2d forces the integers hours and minutes to be of length 2. Further, 06.3f implies that the entire float representation should be 6 characters long (including the '.' ) and have 3 decimal places to the right of the period. 特别是, 0>2d强制整hoursminutes长度为2.此外, 06.3f意味着整个浮动表示应该是6个字符长(包括'.' )并且在右边有3个小数位。期。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM