如何将浮点数转换为整数,去掉 “0” 和 “,”?

huangapple go评论120阅读模式
英文:

How to convert float to int by dropping "0" and ","?

问题

我有一个浮点变量值为0.9533如何将它转换为一个整数变量使值变为9553
```python
a = ((i.left + i.right) / 2)
a = ("{:.4f}".format(a)) // 得到a: 浮点数 = 0.9533
print(f"结果 1: {a}")
b = int(a * 10000) // 得到b: 整数
print(f"结果 2: {b}")

我收到了一个错误:

结果 1: 0.9533
ValueError: 无效的int()字面值,以10进制为基数:'0.95330.95330...95330'
英文:

I have a float variable with a value of 0.9533. How can I convert it to an int variable so that the value becomes 9553?

a = ((i.left + i.right) / 2)
a = ("{:.4f}".format(a)) //get a: float = 0.9533
print(f"Result 1: {a}")
b = int(a * 10000) //get b: int
print(f"Result 2: {b}")

I get an error:

Result 1: 0.9533
ValueError: invalid literal for int() with base 10: '0.95330.95330...95330'

答案1

得分: 1

这应该有效!

a: float = 0.9533 # 在这里获取数字。
b: int = int(str(a).split('.')[1])

这将把 float 转换为 string,然后使用Python的 split 方法将其按照'.'字符分割,然后获取返回数组的第二个元素(索引1),并将其转换回int类型。

英文:

This should work!

a: float = 0.9533 # Get the number here.
b: int = int(str(a).split('.')[1])

This converts the float to a string, then uses Python's split method for string to split it by the '.' character, then gets the second element of the returned array (index 1), and converts that back into an int.

答案2

得分: 0

以下是翻译好的部分:

import decimal

def to_int(num):
  d = decimal.Decimal(str(num))
  exponent = d.as_tuple().exponent * -1
  return int(num * (10 ** (exponent)))

to_int(0.9553) # 9553
英文:

Here is a more general solution that will work with any number.

import decimal

def to_int(num):
  d = decimal.Decimal(str(num))
  exponent = d.as_tuple().exponent * -1
  return int(num * (10 ** (exponent)))

to_int(0.9553) # 9553

</details>



# 答案3
**得分**: 0

Initially, the number was 0.953381023. It was necessary to round to 4 digits after the dot, so I used formatting.

This solution helped me:

b = int((a * 10000)[2:6])

<details>
<summary>英文:</summary>

Initially, the number was 0.953381023.. . It was necessary to round to 4 digits after the dot, so I used formatting.

This solution helped me:

    b = int((a * 10000)[2:6])

</details>



# 答案4
**得分**: 0

a = .0004251
b, c = map(str, map(int, str(a).split('.', 1)))
print(int(b + c))

Output:

4251


<details>
<summary>英文:</summary>

a = .0004251
b,c = map(str,map(int,str(a).split('.',1)))
print(int(b+c))

Output:

4251


</details>



huangapple
  • 本文由 发表于 2023年2月19日 10:27:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/75497639.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定