-
-
Notifications
You must be signed in to change notification settings - Fork 19
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Floating point issues #17
Comments
@xxczaki do you have any idea what could be wrong? |
When converting currencies, the input value is automatically multiplied by 100 then divided by 100 after the computation: Because of a JavaScript quirk, import getRate from './lib/get-rate';
import {Options} from './lib/options';
import parse from './utils/parser';
+import Big from 'big.js';
/**
* Function, which converts currencies based on provided rates.
*
* @param {number | string} amount - Amount of money you want to convert.
* @param {Object} options - Conversion options.
* @return {number} Conversion result.
*
* @example
* const rates = {
* GBP: 0.92,
* EUR: 1.00,
* USD: 1.12
* };
*
* convert(10, {from: 'EUR', to: 'GBP', base: 'EUR', rates}); //=> 9.2
*/
export default function convert(amount: number | string, {from, to, base, rates}: Options): number {
// If provided `amount` is a string, use parsing
if (typeof amount === 'string') {
const data = parse(amount);
- return (data.amount * 100) * getRate(base, rates, data.from ?? from, data.to ?? to) / 100;
+ from = data.from ?? from;
+ to = data.to ?? to;
}
- return (amount * 100) * getRate(base, rates, from, to) / 100;
+ return new Big(amount).multiply(getRate(base, rates, from, to)).toNumber();
} |
Sorry for the inactivity! I just released 3.0.0 with many improvements, including integration with big.js 😄 |
I wrote this simple script using version
2.5.0
And the output is
0.8234999999999999
. I was expecting to received0.8235
, if I runconsole.log(convert(10, {from: "USD", to: "EUR", rates}))
I get a nice value of8.235
.The text was updated successfully, but these errors were encountered: