简体   繁体   English

如果第一个小数点 > 3,自定义四舍五入到下一个 integer?

[英]Custom round up to next integer if first decimal point is > 3?

How can I round up a float to next integer only if the first digit after decimal is >3.仅当小数点后的第一个数字大于 3 时,如何将浮点数舍入到下一个 integer。

my_round(0.0546) should be 0. my_round(0.4) should be 1, my_round(1.35) should be 2. my_round(0.0546)应该是my_round(0.4)应该是 1, my_round(1.35)应该是 2。

Take the input as a string or else if you have it as a float convert it to a string using the str().将输入作为字符串,或者如果您将其作为浮点数,则使用 str() 将其转换为字符串。

After making it to a string turn it to be a list.将其转换为字符串后,将其转换为列表。 validate the index second (third position on the list) whether it is greater than or equal to 3 or not.验证索引第二个(列表中的第三个 position)是否大于或等于 3。

if yes take the index zero value from the list and change it to int and increment with one or else change to int that it, check the sample code below.如果是,则从列表中获取索引零值并将其更改为 int 并以 1 递增,否则更改为 int,请检查下面的示例代码。

x = (input())#with input() the data will be taken as str directly if you have float data convert using str()
lis = list(x)
element = int(lis[2])
if element >=3:
    x = int(lis[0]) + 1
else:
    x = int(lis[0])
print (x)

Yes, forgot that cause, but you can get the required operation with below code.是的,忘记了这个原因,但是您可以使用以下代码获得所需的操作。

x = (input())#with input() the data will be taken as str directly if you have float data convert using str()
lis = list(x)

pos = lis.index('.')

element = int(lis[pos+1])
new_lis = lis[0:pos]
final_data = ''.join(new_lis)

if element >=3:
    x = int(final_data) + 1
else:
    x = int(final_data)
print (x)

identify the index of '.'识别'.'的索引and separate a new list until the '.'并分隔一个新列表,直到“。” index and turn it in to a string using.join() operator.索引并将其转换为字符串 using.join() 运算符。

Validate the next value after decimal and increment the value which is formed after join operator.验证小数点后的下一个值并增加连接运算符后形成的值。

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

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