How to use math-expression-evaluator - 9 common examples

To help you get started, we’ve selected a few math-expression-evaluator examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github MoOx / reduce-css-calc / index.js View on Github external
var unit = units[0] || ""

    if (unit === "%") {
      // Convert percentages to numbers, to handle expressions like: 50% * 50% (will become: 25%):
      // console.log(expression)
      expression = expression.replace(/\b[0-9\.]+%/g, function(percent) {
        return parseFloat(percent.slice(0, -1)) * 0.01
      })
    }

    // Remove units in expression:
    var toEvaluate = expression.replace(new RegExp(unit, "gi"), "")
    var result

    try {
      result = mexp.eval(toEvaluate)
    }
    catch (e) {
      return functionIdentifier + "(" + expression + ")"
    }

    // Transform back to a percentage result:
    if (unit === "%") {
      result *= 100
    }

    // adjust rounding shit
    // (0.1 * 0.2 === 0.020000000000000004)
    if (functionIdentifier.length || unit === "%") {
      result = Math.round(result * decimalPrecision) / decimalPrecision
    }
github sx1989827 / DOClever / node_modules / reduce-css-calc / index.js View on Github external
var unit = units[0] || ""

    if (unit === "%") {
      // Convert percentages to numbers, to handle expressions like: 50% * 50% (will become: 25%):
      // console.log(expression)
      expression = expression.replace(/\b[0-9\.]+%/g, function(percent) {
        return parseFloat(percent.slice(0, -1)) * 0.01
      })
    }

    // Remove units in expression:
    var toEvaluate = expression.replace(new RegExp(unit, "gi"), "")
    var result

    try {
      result = mexp.eval(toEvaluate)
    }
    catch (e) {
      return functionIdentifier + "(" + expression + ")"
    }

    // Transform back to a percentage result:
    if (unit === "%") {
      result *= 100
    }

    // adjust rounding shit
    // (0.1 * 0.2 === 0.020000000000000004)
    if (functionIdentifier.length || unit === "%") {
      result = Math.round(result * decimalPrecision) / decimalPrecision
    }
github eez-open / studio / packages / project-editor / components / PropertyGrid.tsx View on Github external
onKeyDown(event: React.KeyboardEvent) {
        if (event.keyCode === 13) {
            if (this.props.propertyInfo.type === PropertyType.Number) {
                try {
                    var mexp = require("math-expression-evaluator");
                    const newValue = mexp.eval(this._value);
                    if (newValue !== undefined && newValue !== this._value) {
                        this.props.updateObject({
                            [this.props.propertyInfo.name]: newValue
                        });
                    }
                } catch (err) {
                    console.error(err);
                }
            }
        }
    }
github cliffordfajardo / cato / app / common / utils.js View on Github external
utils.isValidMathExpression = function isValidMathExpression(userInput) {
  try {
    mathexp.eval(userInput);
    return true;
  }
  catch(exception) {
    return false;
  }
}
github LenoxBot / LenoxBot / commands / utility / calculator.js View on Github external
exports.run = (client, msg, args, lang) => {
	if (args.length < 1) {
		return msg.channel.send(lang.calculator_noinput);
	}

	const question = args.join(' ');

	let answer;
	try {
		answer = math.eval(question);
	} catch (err) {
		return msg.channel.send(lang.calculator_invalid);
	}

	const embed = new Discord.RichEmbed()
		.setDescription(`**${lang.calculator_calculation}**\n\`\`\`\n${question}\n\`\`\` **${lang.calculator_result}**\n\`\`\`\n${answer}\n\`\`\``)
		.setAuthor(`${msg.author.tag}`, msg.author.displayAvatarURL)
		.setColor('#0066CC');
	msg.channel.send({ embed });
};
github LenoxBot / LenoxBot / commands / currency / math.js View on Github external
let response;
		try {
			response = await msg.channel.awaitMessages(msg2 => msg.author.id === msg2.author.id, {
				max: 1,
				time: 7000,
				errors: ['time']
			});
		} catch (error) {
			let currentCredits = msg.client.provider.getUser(msg.author.id, 'credits');
			currentCredits -= 10;
			await msg.client.provider.setUser(msg.author.id, 'credits', currentCredits);

			return msg.reply(lang.math_timepassed);
		}

		const mathCalculation = await math.eval(`${firstNumber} ${signs[sign]} ${secondNumber}`);

		if (mathCalculation === Number(response.first().content)) {
			const currentMathematics = msg.client.provider.getUser(msg.author.id, 'mathematics');
			currentMathematics.points += 2;
			await msg.client.provider.setUser(msg.author.id, 'mathematics', currentMathematics);

			const mathLevel = Math.floor(1.5 * Math.sqrt(msg.client.provider.getUser(msg.author.id, 'mathematics').points + 1));
			if (mathLevel > msg.client.provider.getUser(msg.author.id, 'mathematics').level) {
				const currentMathematics2 = msg.client.provider.getUser(msg.author.id, 'mathematics');
				currentMathematics2.level = mathLevel;
				await msg.client.provider.setUser(msg.author.id, 'mathematics', currentMathematics2);
			}

			let currentCredits = msg.client.provider.getUser(msg.author.id, 'credits');
			currentCredits += 15 + Math.floor(msg.client.provider.getUser(msg.author.id, 'mathematics').level / 5);
			await msg.client.provider.setUser(msg.author.id, 'credits', currentCredits);
github RayzrDev / SharpBot / src / commands / Utility / calculator.js View on Github external
exports.run = (bot, msg, args) => {
    if (args.length < 1) {
        throw 'You must provide a equation to be solved on the calculator';
    }

    const question = args.join(' ');
    const answer = math.eval(question);

    if (answer) {
        msg.delete();
        msg.channel.send({
            embed: bot.utils.embed('', stripIndents`
                **Equation:**\n\`\`\`\n${question}\n\`\`\`
                **Answer:**\n\`\`\`\n${answer}\n\`\`\`
                `)
        }).catch(msg.error);
    }
};
github cliffordfajardo / cato / app / common / utils.js View on Github external
utils.isIncompleteMathExpression = function isIncompleteMathExpression(userInput) {
  try {
    mathexp.eval(userInput);
    return false;
  }
  catch(exception) {
    if(exception.message === "complete the expression" && userInput !== '') {
      return true;
    }
  }
}
github solobat / Steward / extension / js / plugins / other / calculate.js View on Github external
function onInput(query) {
    let data = [];
    if (this.term.startsWith('calc ') && query) {
        this.render(query);
        return;
    }
    try {
        const result = mathexp.eval(this.str);
        data = [
            {
                key: title,
                icon: icon,
                title: result,
                desc: subtitle
            }
        ];
    } catch (e) {
        data = null;
    }

    return Promise.resolve(data);
}

math-expression-evaluator

A flexible math expression evaluator

MIT
Latest version published 3 months ago

Package Health Score

75 / 100
Full package analysis

Popular math-expression-evaluator functions