0

I'm very new to JavaScript, and am trying to use decimal.js, for a project that requires its fractional exponents.

I've been trying every variation that I see in examples, but my variable declarations are failing, causing the script to abort. The result is a blank document.

I've stripped the script down, to include just what I think will be needed for this question.

<HTML>
<HEAD>
<TITLE>My First Script</TITLE>
<script src="http://mikemcl.github.io/decimal.js"></script>
<!--
<script src="https://unpkg.com/mathjs/dist/math.js"></script>
-->

<HR>
<H1>Title</H1>
<HR>
</HEAD>

<BODY>
<SCRIPT LANGUAGE="JavaScript"> <!--
function myFunction(parm) {
    var Decimal         = require('decimal.js')
    Decimal.set({precision: 200});
    var dn              = new Decimal(parm)

    document.write(dn)
}

myFunction(123.456789)

// --> </SCRIPT>
</BODY>
</HTML>

1 Answers1

0

I've only used decimal.js before as an npm package, not as a script loaded directly into a browswer, but require('decimal.js') is not how you'd load this script in a browser, and you definitely wouldn't want to load it over and over again each time your function is called.

Try just taking this line out: var Decimal = require('decimal.js'), and see how far you get. Decimal should already be defined as a global variable by loading the script.

Also, if you want to get the full precision 'decimal.js' offers, initialize value with string values, not numeric values, like this:

myFunction('123.456789')

Otherwise you'll never get any more precision than a regular JavaScript number provides.

kshetline
  • 12,547
  • 4
  • 37
  • 73
  • Sorry, trying to format this comment. :) @kshetline I modified the function, and the result is that the first document write operation works, but the script aborts, before the rest. 'code' – Paul Adamson Sep 02 '19 at 04:15
  • I don't see anything in your code that's left to execute after the first `document.write`. What more do you expect to happen? – kshetline Sep 02 '19 at 04:31
  • document.write("step 0") writes step 0 then the script fails, on the next line of code Decimal.set... so document.write("step 1") and all of the lines after, never execute. – Paul Adamson Sep 02 '19 at 04:36
  • You seem to be referring to code that I don't see posted in your example, I see no `document.write("step 0")` above. – kshetline Sep 02 '19 at 04:49
  • The problem was the src link. And my downloaded file wasn't linking either, because of a Chromebook path issue. The answer is simply to put the htm file in the same folder as decimal.js, and use the short link for src. – Paul Adamson Sep 02 '19 at 06:05