В настоящее время я работаю над функцией калькулятора для моего бота Discord. Я сделал команду, которая получает рыночную цену товара Steam, а затем вычисляет ее по формуле: ([price] - [price * 0.15]) * amount of cases, где 0,15 - рыночная комиссия. Вот тут и проявляется проблема.
Программа видит json.lowest_price как слово, а не как число (я думаю). В результате бот отправляет сообщение с NaN. Я понятия не имею, как заставить мой код правильно отображать JSON как число.
Вот мой код:
const Discord = require('discord.js');
const fetch = require('node-fetch');
const client = new Discord.Client();
client.login('[TOKEN]');
client.on('ready', () => {
console.info(`Logged in as TEST`);
});
//////////////////////////////////
const prefix = "!";
client.on('message', message =>{
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
if (command === 'calculate') {
if (!args.length){
return message.channel.send(`Invalid argument`);
} else if (args[0] === 'breakout'){
fetch(
'https://steamcommunity.com/market/priceoverview/?appid=730&market_hash_name=Operation%20Breakout%20Weapon%20Case¤cy=6',
)
.then((res) => res.json())
.then((json) =>
message.channel.send(
`From ${args[1]] breakout cases you will get ${((json.lowest_price)-((json.lowest_price)*0.15))*(args[1])}`,
),
)
.catch((error) => {
console.info(error);
message.channel.send('tracking breakout price failed');
});
}
}
});



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Ответ включает lowest_price в виде строки (например, "7,89zł"). Кажется, что API включает форматированную валюту в поле lowest_price, поэтому вы получаете NaN, когда работаете с ним.
Вы можете вручную преобразовать его в число, удалив символ валюты, точки и заменив запятые точками:
function getNumberFromCurrency(currency) {
return Number(
currency
.replace(/[zł.]/g, '')
.replace(',', '.')
)
}
const amount = '10';
const lowestPrice = "7,89zł";
const lowestPriceValue = getNumberFromCurrency(lowestPrice);
const finalPrice = (lowestPriceValue - lowestPriceValue * 0.15) * amount;
console.info({ lowestPriceValue, finalPrice });
// => 7.89, 67.065Но я бы посоветовал вам установить пакет currency.js, так как с ним действительно легко работать. Он может получить значение из любой валюты и имеет встроенное умножение, вычитание и т. д. Все, что вам нужно, чтобы использовать формулу, которую вы упомянули выше. Посмотрите рабочий код ниже:
const currency = require('currency.js');
// ...
// ...
client.on('message', (message) => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
// you can change the format, localising the decimal and/or delimiter
const zloty = (value) =>
currency(value, { symbol: 'zł', separator: '.', decimal: ',' });
if (command === 'calculate') {
if (!args.length) {
return message.channel.send(`Invalid argument`);
} else if (args[0] === 'breakout') {
fetch(
'https://steamcommunity.com/market/priceoverview/?appid=730&market_hash_name=Operation%20Breakout%20Weapon%20Case¤cy=6'
)
.then((res) => res.json())
.then((json) => {
// calculate the final price using currency.js only
const finalPrice = zloty(
zloty(json.lowest_price)
.subtract(
zloty(json.lowest_price)
.multiply(0.15)
)
)
.multiply(args[1])
.format();
message.channel.send(`From ${args[1]} breakout cases you will get ${finalPrice}`);
})
.catch((error) => {
console.info(error);
message.channel.send('tracking breakout price failed');
});
}
}
});