【发布时间】:2022-06-20 22:38:18
【问题描述】:
我有一个部署到 Heroku 的 Django 项目。我注意到当我出于某种原因使用较小的数字时,计算不起作用。在我的本地 Windows 机器上一切正常。
例如,这个计算newBalance = Decimal(str(userObj.user_coins)) - Decimal(str(betValue)) 当计算为 2000 - 12 时,我得到的答案是 2.0E+3 而不是 1988。如果计算是 2000 - 120,我得到的答案是 1900 或 1.9E+3而不是 1880。在我的本地机器上,它工作正常。
我不明白这里可能出了什么问题。
//Template script
$('.bet-submit').click(function() {
const betValue = document.getElementById('bet-value').value
betSocket.send(JSON.stringify({
'id': id,
'betValue': betValue
}))
})
betSocket.onmessage = function(e) {
const data = JSON.parse(e.data)
update_coins()
for(const key in data.bets){
document.querySelector('#bets').innerHTML += '<span>' +data.bets[key].bet_value +'$</span>'
}
}
function update_coins() {
$.ajax({
method: "POST",
headers: { "X-CSRFToken": token },
url: "/api/coins/",
data: {},
success: function(data) {
document.querySelector('#user_coins').innerHTML = data.coins
}
})
};
//consumers.py
async def receive(self, text_data):
id= data['id']
betValue = data['betValue']
await save_bet(id, betValue)
bets = await get_bets(round)
await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'send_bet',
'bets': bets
}
)
@database_sync_to_async
def save_bet(id, betValue):
userObj = CustomUser.objects.filter(steam_id=steamid)[0]
newBalance = userObj.user_coins - Decimal(betValue)
print(newBalance) // 2.0E+3
CustomUser.objects.filter(steam_id=steamid).update(user_coins=newBalance)
...
@database_sync_to_async
def get_bets(round):
...
bets = {}
for idx, bet in enumerate(betsObj):
bets[str(idx)] = {}
bets[str(idx)].update({
...,
'bet_value': str(bet.bet_value),
})
return bets
【问题讨论】:
-
我将数字保存到数据库,然后再次显示在前端,数字计算不正确。 @jfaccioni
-
userObj.user_coints的底层类型是什么?是aDecimalField,还是别的什么?例如,如果它是aFloatField,那么您在 Python 中使用小数和字符串所做的所有工作都无关紧要:该值在存储时会丢失精度,并且使用str()包装数据库中的非理性值不会不要让它变得理性。 -
userObj.user_coins是一个 DecimalField。 @克里斯 -
betValue是什么? (如果user_coins是一个小数,你不应该需要Decimal(str(...))围绕它。我建议你删除它,因为它没有做任何有用的事情,它表明user_coins可能不是十进制值。) -
如果它已经是一个字符串,你为什么要把它包装在
str(...)中?同样,这是不必要的,而且非常令人困惑。 “我将列表中的值保存为字符串并将其发送到模板”—请edit 将相关代码作为minimal reproducible example 放入您的问题中。描述远不如展示清晰。
标签: python python-3.x django heroku