Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

199
Visualizações
Program not adding numbers properly

I'm not that inexperienced in javascript, but this is just confusing me. I'm trying to make an economy system for my discord bot, and I'm using mongodb for it. Right now, I'm making a deposit command, and what I'm doing is simply subtracting the amount given in the command, from the user's wallet, and adding it to the user's bank account. Code:


            const balanceProfile = await client.createBalance(message.member);
            const amount = args[0];
            if(isNaN(args[0])) return message.reply(`Specify an amount to deposit.`);
            if(amount > balanceProfile.wallet) return message.reply(`Too much money to deposit.`);
            
            try {
                await Balance.findOneAndUpdate({
                    _id: balanceProfile.id, 
                    wallet: balanceProfile.wallet - amount, 
                    bank: balanceProfile.bank + amount
                });
            } catch (error) {
                console.log(error);
            }
            message.reply(`Successfully deposited ${amount} moneyz to da bank!`)
        }
    }

Mongo Schema:

const mongoose = require('mongoose');
const balanceSchema = new mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    memberId: String,
    wallet: { type: Number, default: 0 },
    bank: { type: Number, default: 0 },
    daily: { type: Number }
});

module.exports = mongoose.model('Balance', balanceSchema, 'balances');

The wallet works fine, it subtracts the amount from the wallet perfectly. However, my problem is that instead of adding the amount to the bank, it literally adds the number to the end of the number. So if I were to deposit 5 dollars to my bank, and I already have 7 dollars in my bank, then I would get 75 dollars in my bank. (I want it to add 5 dollars to my bank, not the literal number 5 to my bank). There aren't any errors, and I have no idea what to search up to solve this, and couldn't find any previous questions about this. Any help would be appreciated.

Sidenote: I tried using the += statement too.

about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

Even though your bank field is declared as a Number, the normal JavaScript type-coercion rules apply and are specified in ECMAScript section 13.15.3 ApplyStringOrNumericBinaryOperator.

If Type(lprim) is String or Type(rprim) is String, then

i. Let lstr be ? ToString(lprim).

ii. Let rstr be ? ToString(rprim).

iii. Return the string-concatenation of lstr and rstr.

You're getting the value to add from here:

const amount = args[0];
if(isNaN(args[0])) return message.reply(`Specify an amount to deposit.`);

args[0] is likely a string and adding a string to a number coerces the number into a string:

const balance = 7;
const deposit = '5';

console.log('New balance is', balance + deposit);

It looks like you want to parse args[0] first:

const balance = 7;
const deposit = Number('5');

console.log('New balance is', balance + deposit);

So something like this:

const amount = Number(args[0]);
if(isNaN(amount)) return message.reply(`Specify an amount to deposit.`);
about 4 years ago · Santiago Gelvez Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda