【问题标题】:Python: How To Display String In 8 Decimal PlacesPython:如何在 8 个小数位中显示字符串
【发布时间】:2018-02-14 05:26:56
【问题描述】:

对不起,这个奇怪的标题,但我真的不知道如何解释。基本上,我有这个从 API 中获取的代码,但是,如果数值试图显示低。 (比方说 0.0008 或更低)它将显示为一串数字,最后是一个 e。

示例:8.888e-5 或随机的。

如何让它显示为数字?比如:每个 PLSR 0.00084BTC。

(Python 3.6.4) 它必须保存为字符串才能工作!

为什么这不是重复:虽然另一个线程找到了与我想要的类似的答案,但它并没有准确解释如何将它合并到我已经将其转换为字符串的代码中。将其转换为字符串后,我会将其覆盖在上面还是..?

代码:

import requests
import discord
import asyncio

url = 'https://cryptohub.online/api/market/ticker/PLSR/'
response = requests.get(url)
data = response.json()['BTC_PLSR']

client = discord.Client()

@client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')

price = print('PLSR Price:', data['last'])
pulsar = str(data['last'])

await client.change_presence(game=discord.Game(name="PLSR Price: " + pulsar))

【问题讨论】:

标签: python string python-3.x numbers discord


【解决方案1】:

您看到的是科学记数法。 8.888e+2 表示 8.888x102

如果您不喜欢默认设置,则需要使用 String Formatting Mini-Language。 Python 在格式化方面经历了一些变化。以下是一些选项:

>>> value = .000008888  
>>> value                           # default display of small number
8.888e-06
>>> print('%.8f' % value)           # old, deprecated format.
0.00000889
>>> print('{:.8f}'.format(value))   # newer format.
0.00000889
>>> print(f'{value:.8f}')           # newest format in Python 3.6.
0.00000889

请注意,.8f 表示“小数点后 8 位,固定浮点数”。

更多信息:

根据您的评论,您可以使用以下格式以科学计数法格式化字符串:

>>> pulsar = '8.888e+2'
>>> f'PLSR Price: {float(pulsar):.2f}'
'PLSR Price: 888.80'

【讨论】:

  • 这有助于解释事情,但我将如何将它实现到我的代码中?由于我将列表转换为字符串,因此无法这样做,这样做会出错。
  • @Blake 请显示一个简单的示例,而不是链接。链接中断,这个问题对未来的观众没有用处。请参阅minimal reproducible example 指南。要添加代码,请剪切并粘贴到问题中,突出显示它,然后使用{} 按钮格式化为代码。
  • 添加了它,虽然真的很难弄清楚。
  • await client.change_presence(game=discord.Game(name=f'PLSR Price: {float(pulsar):.2f}')) - 这不会以正确的格式返回。我是不是做错了什么?
【解决方案2】:

当数字变得足够大或足够小时,Python 使用scientific notation 引用它们。这并不意味着该值不正确或“奇怪”,它只是以不同的格式显示。

如要强制显示 8 位数字,您需要对其进行格式化:

print('%.8f' % value)

【讨论】:

  • 出现错误:必须是实数,而不是 str
  • @BlakeXavier 首先将您的字符串转换为浮点数:print('%.8f' % float(value))
  • @BlakeXavier 删除此行中的print 和周围的()x = print ('%.8f' % float(pulsar))。您现在也从(大概)float (data['last']) 转换为string,然后又转换回float。跳过将其转换为string
  • @BlakeXavier 请按照马克的回答,他正是你需要的。
猜你喜欢
  • 2012-05-17
  • 2012-07-27
  • 1970-01-01
  • 1970-01-01
  • 2016-09-28
  • 2020-03-21
  • 1970-01-01
  • 2013-04-07
  • 2011-06-17
相关资源
最近更新 更多