2

I'm currently working on a calculator feature for my discord bot. I've made a command that fetches steam market item price, and then calculate it according to the formula: ([price] - [price * 0.15]) * amount of cases, where 0.15 is the market fee. That's where the problem shows up.

Program sees json.lowest_price as a word, not as a number (I think). As a result, bot sends a message with NaN. I have no idea how to make my code seeing JSON thingy as a number properly.

Here's my code:

const Discord = require('discord.js');
const fetch = require('node-fetch');
const client = new Discord.Client();

client.login('[TOKEN]');

client.on('ready', () => {
  console.log(`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&currency=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.log(error);
      message.channel.send('tracking breakout price failed');
    });
  }
}
});

Message that appear

Zsolt Meszaros
  • 21,961
  • 19
  • 54
  • 57
Brunon
  • 31
  • 2

1 Answers1

4

The response includes the lowest_price as a string (like "7,89zł"). It seems the API does include a formatted currency in the lowest_price field, that's why you receive NaN when you work with it.

You could convert it manually to a number by removing the currency symbol, removing dots, and replacing commas with dots:

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.log({ lowestPriceValue, finalPrice });
// => 7.89, 67.065

But I'd suggest you to install the currency.js package as it's really easy to work with it. It can get the value from any currency, and has built-in multiplication, subtraction, etc. Everything you need to use the formula you mentioned above. Check out the working code below:

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&currency=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.log(error);
          message.channel.send('tracking breakout price failed');
        });
    }
  }
});

enter image description here

Zsolt Meszaros
  • 21,961
  • 19
  • 54
  • 57