Skip to content

Commit f5c6260

Browse files
dferber90montezume
authored andcommitted
fix(money-input): avoid messing with floating point numbers (#446)
1 parent 792c505 commit f5c6260

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

src/components/inputs/money-input/money-input.js

+12-1
Original file line numberDiff line numberDiff line change
@@ -221,7 +221,18 @@ export const createMoneyValue = (currencyCode, rawAmount) => {
221221
currencyCode,
222222
centAmount,
223223
preciseAmount: parseInt(
224-
amountAsNumber * 10 ** fractionDigitsOfAmount,
224+
// Here we need to convert a number like 8.066652 to its centamount
225+
// We could do that by multiplying it with 10 ** number-of-fraction-digits
226+
// but then we'll run into problems with JavaScript's floating point
227+
// number precision and end up with 8066651.9999999, and then parseInt
228+
// cuts off the remainder.
229+
// So instead of using maths to convert the number, we just replace
230+
// the dot inside the number which does the same thing.
231+
// We don't need to replace "," as well, as numbers always us a dot
232+
// when converted using String().
233+
//
234+
// The mathematical way: amountAsNumber * 10 ** fractionDigitsOfAmount,
235+
String(amountAsNumber).replace('.', ''),
225236
10
226237
),
227238
fractionDigits: fractionDigitsOfAmount,

src/components/inputs/money-input/money-input.spec.js

+13
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,19 @@ describe('MoneyInput.convertToMoneyValue', () => {
160160
fractionDigits: 2,
161161
});
162162

163+
expect(
164+
MoneyInput.convertToMoneyValue({
165+
currencyCode: 'EUR',
166+
amount: '8.066652',
167+
})
168+
).toEqual({
169+
type: 'highPrecision',
170+
currencyCode: 'EUR',
171+
centAmount: 807,
172+
preciseAmount: 8066652,
173+
fractionDigits: 6,
174+
});
175+
163176
// This test ensures that rounding is used instead of just cutting the
164177
// number of. Cutting it of would result in an incorrect 239998.
165178
expect(

0 commit comments

Comments
 (0)