我是JavaScript的新手(我来自Java背景),我正在尝试用少量资金进行一些财务计算。
我原来的意思是:
<script type="text/javascript">
var normBase = ("[price]").replace("$", "");
var salesBase = ("[saleprice]").replace("$", "");
var base;
if (salesBase != 0) {
base = salesBase;
} else {
base = normBase;
}
var per5 = (base - (base * 0.05));
var per7 = (base - (base * 0.07));
var per10 = (base - (base * 0.10));
var per15 = (base - (base * 0.15));
document.write
(
'5% Off: $' + (Math.ceil(per5 * 100) / 100).toFixed(2) + '<br/>' +
'7% Off: $' + (Math.ceil(per7 * 100) / 100).toFixed(2) + '<br/>' +
'10% Off: $' + (Math.ceil(per10 * 100) / 100).toFixed(2) + '<br/>' +
'15% Off: $' + (Math.ceil(per15 * 100) / 100).toFixed(2) + '<br/>'
);
</script>
除非总是向上舍入(Math.ceil
),否则效果很好。 Math.floor
有同样的问题,Math.round
也不适合花车。
在Java中,我会完全避免使用浮点数,但是在JavaScript中似乎没有默认包含可比较的内容。
问题是,所提到的所有库都被破坏或用于其他目的。 jsfromhell.com/classes/bignumber
库非常接近我所需要的,但是我的舍入和精度都有奇怪的问题......无论我将Round Type设置为什么,它似乎都是自己决定的。因此,例如,精度为2的3.7107和ROUND_HALF_UP
的圆形类型在应该为3.71时会以3.72的形式结束。
我也尝试过@JasonSmith BigDecimal库(来自Java的BigDecimal的机械加工端口),但似乎是node.js,我没有选择运行。
我如何使用vanilla JavaScript(并且可靠)来实现这一点,或者是否有一个现代的(上面提到的那些现在已经存在多年了)我可以使用的库是否可以维护并且没有被破坏?
答案 0 :(得分:5)
我喜欢使用accounting.js
进行数字,金钱和货币格式化。
答案 1 :(得分:3)
由于我们对 BigInt
有本机支持,因此实现 BigDecimal
不再需要太多代码。
这是一个基于 BigDecimal
的 BigInt
类,具有以下特征:
BigInt
,乘以 10 的幂以包含小数。BigInt
值进行。add
、subtract
、multiply
和 divide
的参数可以是数字、字符串或 BigDecimal
的实例BigDecimal
被视为不可变的。toString
方法重新引入小数点。BigDecimal
可以强制转换为数字(通过隐式调用 toString
),但这显然会导致精度损失。class BigDecimal {
// Configuration: constants
static DECIMALS = 18; // number of decimals on all instances
static ROUNDED = true; // numbers are truncated (false) or rounded (true)
static SHIFT = BigInt("1" + "0".repeat(BigDecimal.DECIMALS)); // derived constant
constructor(value) {
if (value instanceof BigDecimal) return value;
let [ints, decis] = String(value).split(".").concat("");
this._n = BigInt(ints + decis.padEnd(BigDecimal.DECIMALS, "0")
.slice(0, BigDecimal.DECIMALS))
+ BigInt(BigDecimal.ROUNDED && decis[BigDecimal.DECIMALS] >= "5");
}
static fromBigInt(bigint) {
return Object.assign(Object.create(BigDecimal.prototype), { _n: bigint });
}
add(num) {
return BigDecimal.fromBigInt(this._n + new BigDecimal(num)._n);
}
subtract(num) {
return BigDecimal.fromBigInt(this._n - new BigDecimal(num)._n);
}
static _divRound(dividend, divisor) {
return BigDecimal.fromBigInt(dividend / divisor
+ (BigDecimal.ROUNDED ? dividend * 2n / divisor % 2n : 0n));
}
multiply(num) {
return BigDecimal._divRound(this._n * new BigDecimal(num)._n, BigDecimal.SHIFT);
}
divide(num) {
return BigDecimal._divRound(this._n * BigDecimal.SHIFT, new BigDecimal(num)._n);
}
toString() {
const s = this._n.toString().padStart(BigDecimal.DECIMALS+1, "0");
return s.slice(0, -BigDecimal.DECIMALS) + "." + s.slice(-BigDecimal.DECIMALS)
.replace(/\.?0+$/, "");
}
}
// Demo
var a = new BigDecimal("123456789123456789876");
var b = a.divide("10000000000000000000");
var c = b.add("9.000000000000000004");
console.log(b.toString());
console.log(c.toString());
console.log(+c); // loss of precision when converting to number
答案 2 :(得分:1)
答案 3 :(得分:0)
Big.js
很棒,但对我来说太笨重了。
我目前正在使用以下使用 BigInt 的任意精度。仅支持加、减、乘、除。调用 set_precision(8);
将精度设置为 8 位小数。
舍入模式为 ROUND_DOWN。
class AssertionError extends Error {
/**
* @param {String|void} message
*/
constructor (message) {
super(message);
this.name = 'AssertionError';
if (Error.captureStackTrace instanceof Function) {
Error.captureStackTrace(this, AssertionError);
}
}
toJSON () {
return { name: this.name, message: this.message, stack: this.stack };
}
/**
* @param {Boolean} value
* @param {String|void} message
*/
static assert (value, message) {
if (typeof value !== 'boolean') {
throw new Error('assert(value, message?), "value" must be a boolean.');
}
if (message !== undefined && typeof message !== 'string') {
throw new Error('assert(value, message?), "message" must be a string.');
}
if (value === false) {
throw new AssertionError(message);
}
}
}
module.exports = AssertionError;
const AssertionError = require('./AssertionError');
let precision = 2;
let precision_multiplier = 10n ** BigInt(precision);
let max_safe_integer = BigInt(Number.MAX_SAFE_INTEGER) * precision_multiplier;
/**
* @param {Number} value
*/
const set_precision = (value) => {
AssertionError.assert(typeof value === 'number');
AssertionError.assert(Number.isFinite(value) === true);
AssertionError.assert(Number.isInteger(value) === true);
AssertionError.assert(value >= 0 === true);
precision = value;
precision_multiplier = 10n ** BigInt(precision);
max_safe_integer = BigInt(Number.MAX_SAFE_INTEGER) * precision_multiplier;
};
/**
* @param {Number} value
*/
const to_bigint = (value) => {
AssertionError.assert(typeof value === 'number');
AssertionError.assert(Number.isFinite(value) === true);
return BigInt(value.toFixed(precision).replace('.', ''));
};
/**
* @param {BigInt} value
* @param {Number} decimal_places
*/
const to_number = (value) => {
AssertionError.assert(typeof value === 'bigint');
AssertionError.assert(value <= max_safe_integer);
const value_string = value.toString().padStart(2 + precision, '0');
const whole = value_string.substring(0, value_string.length - precision);
const decimal = value_string.substring(value_string.length - precision, value_string.length);
const result = Number(`${whole}.${decimal}`);
return result;
};
/**
* @param {Number[]} values
*/
const add = (...values) => to_number(values.reduce((previous, current) => previous === null ? to_bigint(current) : previous + to_bigint(current), null));
const subtract = (...values) => to_number(values.reduce((previous, current) => previous === null ? to_bigint(current) : previous - to_bigint(current), null));
const multiply = (...values) => to_number(values.reduce((previous, current) => previous === null ? to_bigint(current) : (previous * to_bigint(current)) / precision_multiplier, null));
const divide = (...values) => to_number(values.reduce((previous, current) => previous === null ? to_bigint(current) : (previous * precision_multiplier) / to_bigint(current), null));
const arbitrary = { set_precision, add, subtract, multiply, divide };
module.exports = arbitrary;
const arbitrary = require('./arbitrary');
arbitrary.set_precision(2);
const add = arbitrary.add;
const subtract = arbitrary.subtract;
const multiply = arbitrary.multiply;
const divide = arbitrary.divide;
console.log(add(75, 25, 25)); // 125
console.log(subtract(75, 25, 25)); // 25
console.log(multiply(5, 5)); // 25
console.log(add(5, multiply(5, 5))); // 30
console.log(divide(125, 5, 5)); // 5
console.log(divide(1000, 10, 10)); // 10
console.log(divide(1000, 8.86)); // 112.86681715
console.log(add(Number.MAX_SAFE_INTEGER, 0)); // 9007199254740991
console.log(subtract(Number.MAX_SAFE_INTEGER, 1)); // 9007199254740990
console.log(multiply(Number.MAX_SAFE_INTEGER, 0.5)); // 4503599627370495.5
console.log(divide(Number.MAX_SAFE_INTEGER, 2)); // 4503599627370495.5
console.log(multiply(Math.PI, Math.PI)); // 9.86960437
console.log(divide(Math.PI, Math.PI)); // 1
console.log(divide(1, 12)); // 0.08333333
console.log(add(0.1, 0.2)); // 0.3
console.log(multiply(1.500, 1.3)); // 1.95
console.log(multiply(0, 1)); // 0
console.log(multiply(0, -1)); // 0
console.log(multiply(-1, 1)); // -1
console.log(divide(1.500, 1.3)); // 1.15384615
console.log(divide(0, 1)); // 0
console.log(divide(0, -1)); // 0
console.log(divide(-1, 1)); // -1
console.log(multiply(5, 5, 5, 5)); // 625
console.log(multiply(5, 5, 5, 123, 123, 5)); // 9455625