UNPKG

mathjs

Version:

Math.js is an extensive math library for JavaScript and Node.js. It features a flexible expression parser with support for symbolic computation, comes with a large set of built-in functions and constants, and offers an integrated solution to work with dif

81 lines (72 loc) 1.99 kB
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>math.js | custom separators</title> <style> body, input, select { font: 11pt sans-serif; } input, select, th, #result { padding: 5px 10px; } th { text-align: left; } </style> <script src="../../lib/browser/math.js"></script> </head> <body> <p> This code example shows how to apply custom separators for function arguments and decimal separator. </p> <table> <tr> <th>Argument separator</th> <td> <input id="args" type="text" value=";"> </td> </tr> <tr> <th>Decimal separator</th> <td> <input id="decimals" type="text" value=","> </td> </tr> <tr> <th>Expression</th> <td> <input id="expression" type="text" value="sum(3,4; 2,1; 2,0)" /> <input id="evaluate" type="button" value="Evaluate"> </td> </tr> <tr> <th>Result</th> <td id="result"></td> </tr> </table> <script> // pointers to the input elements const expression = document.getElementById('expression') const evaluate = document.getElementById('evaluate') const result = document.getElementById('result') const args = document.getElementById('args') const decimals = document.getElementById('decimals') // attach event handler to the button evaluate.onclick = function () { // replace the custom separators in the input with the default separators const expr = expression.value .replace(new RegExp('\\' + decimals.value + '|\\' + args.value, 'g'), function (match) { return match === decimals.value ? '.': ',' }) // do the actual evaluation const res = math.evaluate(expr) // replace the default separators in the output with custom separators result.innerHTML = res.toString() .replace(new RegExp(',|\\.', 'g'), function (match) { return match === '.' ? decimals.value : args.value }) } </script> </body> </html>