Skip to content

Commit d4e8a6f

Browse files
authoredJan 3, 2025··
fix: Implemented fix by @Oxean (#14)
* fix: Implemented fix by @Oxean This fixed edge cases when substracting with from/with zero
1 parent f68726f commit d4e8a6f

File tree

2 files changed

+21
-13
lines changed

2 files changed

+21
-13
lines changed
 

‎lib/decimal.js

+9-13
Original file line numberDiff line numberDiff line change
@@ -126,38 +126,34 @@ var as_integer = function (number) {
126126
};
127127

128128
// Helpers
129-
var neg_exp = function (str, position) {
129+
// Helpers
130+
var neg_exp = function (str, position, sign) {
130131
position = Math.abs(position);
131132

132133
var offset = position - str.length;
133134
var sep = DECIMAL_SEPARATOR;
134135

135136
if (offset >= 0) {
136137
str = zero(offset) + str;
137-
sep = '0' + DECIMAL_SEPARATOR;
138+
sep = '0.';
138139
}
139140

140141
var length = str.length;
141142
var head = str.substr(0, length - position);
142143
var tail = str.substring(length - position, length);
143-
144-
if (tail.charAt(0) === '-') {
145-
head = '-' + head;
146-
tail = tail.substr(1);
147-
}
148-
149-
return (head + sep + tail).replace('-' + DECIMAL_SEPARATOR, '-0' + DECIMAL_SEPARATOR);
144+
return sign + head + sep + tail;
150145
};
151146

152-
var pos_exp = function (str, exp) {
147+
var pos_exp = function (str, exp, sign) {
153148
var zeros = zero(exp);
154-
return String(str + zeros);
149+
return String(sign + str + zeros);
155150
};
156151

157152
var format = function (num, exp) {
158-
num = String(num);
153+
var lt0 = num < 0;
154+
num = String(lt0 ? -num : num);
159155
var func = exp >= 0 ? pos_exp : neg_exp;
160-
return func(num, exp);
156+
return func(num, exp, lt0 ? '-' : '');
161157
};
162158

163159
var zero = function (exp) {

‎tests/subtraction.js

+12
Original file line numberDiff line numberDiff line change
@@ -15,3 +15,15 @@ test('subtraction toString conversion', function (t) {
1515
assert.equal(Decimal('123.456').sub('123000'), Decimal.sub('123.456', '123000').toString());
1616
assert.equal(Decimal('100.2').sub('1203.12'), Decimal.sub('100.2', '1203.12').toString());
1717
});
18+
19+
test('subtraction zero', function (t) {
20+
assert.equal(Decimal('0').sub('123000'), '-123000');
21+
assert.equal(Decimal('123000').sub('0'), '123000');
22+
assert.equal(Decimal(0.92).sub(1), '-0.08');
23+
assert.equal(Decimal(1).sub(0.92), '0.08');
24+
assert.equal(Decimal(1).sub(1), '0');
25+
26+
assert.equal(Decimal(0).sub(0.01), '-0.01');
27+
assert.equal(Decimal(0).sub(0.09), '-0.09');
28+
assert.equal(Decimal(0.01).sub(0), '0.01');
29+
});

0 commit comments

Comments
 (0)