[英]Newb question: I'm just having trouble using decimal.js in my script
I'm very new to JavaScript, and am trying to use decimal.js, for a project that requires its fractional exponents. 我对JavaScript还是很陌生,并且正在尝试将小数.js用于需要其小数指数的项目。
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>
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 . 我之前仅将
decimal.js
用作npm软件包,而不是将脚本直接加载到浏览器中,但是require('decimal.js')
并不是您如何在浏览器中加载此脚本,并且您绝对不会不想每次调用函数时都一遍又一遍地加载它。
Try just taking this line out: var Decimal = require('decimal.js')
, and see how far you get. 尝试仅删除这一行:
var Decimal = require('decimal.js')
,然后看看能走多远。 Decimal
should already be defined as a global variable by loading the script. 通过加载脚本,
Decimal
应该已经定义为全局变量。
Also, if you want to get the full precision 'decimal.js' offers, initialize value with string values, not numeric values, like this: 另外,如果您想获得全精度的“ decimal.js”产品,请使用字符串值而不是数字值来初始化值,如下所示:
myFunction('123.456789')
Otherwise you'll never get any more precision than a regular JavaScript number
provides. 否则,您将永远无法获得比常规JavaScript
number
提供的精度更高的精度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.