Giter Site home page Giter Site logo

openexchangerates / money.js Goto Github PK

View Code? Open in Web Editor NEW
1.4K 1.4K 126.0 338 KB

money.js is a tiny (1kb) javascript currency conversion library, for web & nodeJS

Home Page: http://openexchangerates.github.io/money.js

License: MIT License

CSS 66.17% JavaScript 33.83%

money.js's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

money.js's Issues

Add additional rate that cannot be obtained from API

Hi,

I am trying to include the Ethereum price which is not included in the free version of the Open Exchange Rate API rate.
I think I might be able to make some modifications to make it work.
So I added a function in the money.js as follow:
var append = fx.append = (key, value) => {
fx.rates[key] = value
}
And in my main.js:
fx.rate['ETH'] = 0.00061;
However, this doesn't work. It would be great if anyone can point me a way out.
Sorry, I am new to JS too.
Thanks.

Update internal variable names for consistency

Inside the getRate function, change internal to and from variable names to quote and base, if it wouldn't affect comprehension - this is for consistency with standard terms/labeling in exchange rate calculations.

fxSetup doesn't work with browserify

money is assuming that 'this' will === window in browser environments but this doesn't work with Browserify. As a result, fxSetup can't be accessed and you end up with an error from missing rates.

I changed:
}(this));

To:
}(typeof window === 'undefined' ? this : window));

Adding the latest rates automatically

I can only get this to work if I put the rates in manually:
fx.rates = {
"EUR" : 0.745101, // eg. 1 USD === 0.745101 EUR
"GBP" : 0.647710, // etc...
"HKD" : 7.781919,
"USD" : 1, // always include the base rate (1:1)
/* etc */
}
What I really want is the API to auto update with the latest currency rates.

I wired up the json request:
$.getJSON(
// NB: using Open Exchange Rates here, but you can use any source!
'http://openexchangerates.org/api/latest.json?app_id=[I hid this]', function(data) {
// Check money.js has finished loading:
if (typeof fx !== "undefined" && fx.rates) {
fx.rates = data.rates;
fx.base = data.base;
} else {
// If not, apply to fxSetup global:
var fxSetup = {
rates: data.rates,
base: data.base
}
}
});

But it doesn't with latest currencies. Any ideas?

Consider adding licence

Hi there,

This looks like an awesome library but without a clear Licence file in the root directory, Im not sure this is ok to use in any project.
Would be great if you could add one ? (because a GPL and a CC are free to use both, but do not have the same implications for the using app !)

thx

no license specified (just a copyright notice)

I can't find the license for this code, just a copyright notice?

Please add one somewhere. (ideally it should be in /LICENSE and also at least referenced from the readme and any place where you already have copyright notices)

Thanks!

Uncaught fx error

Hello,

money.js seems like a great library, but I can't seem to get it working. No matter what, I always get: "Uncaught fx error" as the javascript console output and the conversions don't seem to be working.

I get this error on a fresh page with just money.js included and the BASIC convert() function being called. To be more specific, the error also says: "b.convert (anonymous function)"

Any ideas?

Rounding Issue

Seems like converting 100 units of one currency to itself will not always result in 100 units. Example:

fx.base = "USD";
fx.rates = {
"EUR" : 1.745101,
}

Result: Converting 100 EUR to EUR will actually result in 99.9999999999.

Is this something that will be fixed in the library, or do I need to figure out how to do it in my script? (I'm afraid I'm not exactly a js buff, hence the question.)

Thanks!

Can only use hard-coded rates, not those from openexchangerates

Really stuck on what to do here as I keep getting the error 'uncaught fx error' whenever I try to get the live rates (hard coding the rates works fine).

Here's the order I'm loading my scripts in:

<script src="jquery.js" type="text/javascript"></script>
<script src="accounting.min.js" type="text/javascript"></script>
<script src="money.min.js" type="text/javascript"></script>
<script src="myscript.js" type="text/javascript"></script>

And here's my jQuery code (myscript.js):

  /* ****************************************************************** */
    /* !CURRENCY CONVERTOR */
  /* ****************************************************************** */   

  // Set up money.js currencies - get latest rates with ajax:  
  $.getJSON(
    'https://openexchangerates.org/api/latest.json?app_id=[my_app_id]',
    function(data) {
      // Check money.js has finished loading:
      if ( typeof fx !== "undefined" && fx.rates ) {
        fx.rates = data.rates;
        fx.base = data.base;
      } else {
        // If not, apply to fxSetup global:
        var fxSetup = {
          rates : data.rates,
          base : data.base
        }
      }
    }
  );

  /*
  // Only hard-coding the rates like below works
  fx.base = "GBP";
  fx.rates = {
    "EUR" : 1.41, // eg. 1 GBP === 1.41 EUR
    "GBP" : 1, // always include the base rate (1:1)
    "SEK" : 13.18,
    "DKK" : 10.55,
    "NOK" : 13.21,
    "USD" : 1.52,
  }
  */

  // Functions to convert prices on collection and product pages
  function osuConvertCurr(priceContainerParent, priceContainer, currencyContainer, activeCurrency) {
    $(priceContainerParent).each(function() {

      var priceToConvert            = $(this).find(priceContainer).data('gbp-price');
      var priceConverted            = fx.convert(priceToConvert, {from: "GBP", to: activeCurrency});
          priceConverted            = accounting.toFixed(priceConverted, 0);

      $(this).find(priceContainer).text(priceConverted + ' ');
      $(this).find(currencyContainer).text(activeCurrency);

    });
  }
  function osuConvertCartItems(currency) {

    // Convert each item
    $('.actual-price').each(function() {

      var itemPrice                 = $(this).text();
      var itemPriceConverted        = fx.convert(itemPrice, {from: "GBP", to: currency});
          itemPriceConverted        = accounting.toFixed(itemPriceConverted, 0);

      $(this).text(itemPriceConverted + ' ');
      $(this).next().text(currency);

    });

  }
  function osuConvertCartCurr(currency) {

    // Convert subtotal
    var subtotal                    = $('.cart-subtotal--price').text();
    var subtotalConverted           = fx.convert(subtotal, {from: "GBP", to: currency});
        subtotalConverted           = accounting.toFixed(subtotalConverted, 0);

    $('.cart-subtotal').find('.cart-subtotal--price').text(subtotalConverted + ' ');
    $('.cart-subtotal').find('.product-currency').text(currency);

  }

  // Set correct dropdown state based on cookie value
  var cc_cookie = $.cookie('_cc_currency');
  if( cc_cookie == 'USD' ) {
    $('.currency-convertor option[value=USD]').prop("selected", "selected");
  } else if(cc_cookie == 'EUR') {
    $('.currency-convertor option[value=EUR]').prop("selected", "selected");
  } else if(cc_cookie == 'SEK') {
    $('.currency-convertor option[value=SEK]').prop("selected", "selected");
  } else if(cc_cookie == 'DKK') {
    $('.currency-convertor option[value=DKK]').prop("selected", "selected");
  } else if(cc_cookie == 'NOK') {
    $('.currency-convertor option[value=NOK]').prop("selected", "selected");
  } else {
    $('.currency-convertor option[value=GBP]').prop("selected", "selected");
  }

  // Set cookie value based on dropdown
  $('.currency-convertor select').on('change', function() {
    var optionValue = $(this).val();
    $.cookie('_cc_currency', optionValue, { expires: 14, path: '/' });
    location.reload();
  });


  // CONVERT CURRENCIES
  // --------------------------------------------------------------------
  if(cc_cookie !== 'GBP') {

    // Collections and single products
    if($('body').hasClass('template-collection') || $('body').hasClass('template-product')) {
      osuConvertCurr('.product-price', '.actual-price', '.product-currency', cc_cookie);
    }

    // Cart page
    if($('body').hasClass('template-cart')) {
      osuConvertCartItems(cc_cookie);
      osuConvertCartCurr(cc_cookie);
      $('.cart-subtotal p').slideDown('medium');
    }

  }

Any ideas of what's going on?

Thanks,

Osu

Get current exchange rate function

Using this library to create a forex calculator. I would love if there was a way to combine two currencies into a single currency pair that can be used for calculations.

i.e. Currently to find an exchange rate, Base and Rate must be defined separately. Create a variable/method that can store both.

Incorrect Open Exchange Rates

Where do you get the rates from? because I checked the latest rates json, and 1 USD is stated as 7 thousands something IDR, while I'm sure IDR is Indonesian Rupiahs and 1 USD is surely not 7 thousands something :) It should be 8 thousands something, close to 9,000. I checked IDR with GBP is incorrect too, so I'm sure something's wrong with the data.

Alternative for money.js - Cashify

Hi everyone!

I recently created Cashify - Lightweight currency conversion library, successor of money.js ๐Ÿ’ธ

I created this package, because money.js:

  • is not maintained (last commit was ~5 years ago)
  • has over 20 issues open
  • does not support TypeScript
  • has implicit globals
  • does not have any unit tests

Why you should use Cashify?

Clarification on JS coding style

Line no 49
var convert = fx.convert = function(val, opts) {

I'm trying to understand JS coding styles and I found this in money.js as well as underscore.js (you have mentioned it as inspiration the source code).

What's the reason to have a local variable convert when you could have just used fx.convert in it's place?

Be able to get another instance of the module

I hope this project is still maintained... It doesn't really look like it is though.

When using the lib in node, it is not possible to use different rates at different places.
This is due to the fact that the module is a singleton.

I suggest a method to get a fresh instance of fx on which different rates could be set.
It could work like this:

var fx = require('money');
// Global settings
fx.base = 'EUR';
fx.rates = { 'USD': 0.9 };

// convert using the global settings

var myVerySpecialMethod = function () {
  var myLocalFx = fx.clone();
  // these settings are only applied to that local instance
  myLocalFx.base = 'CHF';
  myLocalFx.rates = { 'USD': 2.5 };

  // convert using the local settings
};

This way the current API would still work.

Extend chaining method names to include `base` and `quote`

In money.js, you can chain methods like this:

fx(1000).from("EUR").to("USD"); // 1.2945

These could be aliased as base and quote, for consistency with the naming convention in currency pairs and exchange rate calculations

So they would also be available like this:

fx(1000).base("EUR").quote("USD"); // 1.2945

But only if it doesn't bloat the code too much.

Cannot get it to work on Node.js

Today I ran npm i --save money and tried to get it to work in my Node.js application:

"use strict";

const fx = require('money');
let converted = fx.convert(1000, {from: "GBP", to: "HKD"});

Unfortunately, all I get is this:

node_modules\money\money.js:78
        if ( !rates[to] || !rates[from] ) throw "fx error";

bower support

i'm trying to download money.js from bower (version 0.9.2) and i'm getting this error

bower install money --save
bower cloning git://gitub.com/josscrowcroft/money.js.git
bower caching git://gitub.com/josscrowcroft/money.js.git
bower error status code of git: 128

There were errors, here's a summary of them:
- money status code of git: 128
error: Unknown SSL protocol error in connection to gitub.com:443  while accessing https://gitub.com/josscrowcroft/money.js.git/info/refs?service=git-upload-pack
fatal: HTTP request failed

This happen only with this repos. Any idea ? Thanks

Support currency pairs (e.g. EUR/USD)

A cool potential feature, logged for later - use money.js to get the rate for any given currency pair - if it wouldn't bloat the code too much

// Something like:
fx("EUR/USD").get() // 1.2945

// or:
fx.pair("GBP/AED") // 5.6974

If anyone has thoughts on that, you know what to do.

add it to bower

Hi,

Maybe it's a good idea to list the library in bower :D

hope you do,

specktator

Error in render : Fx error when rendering it as a module

I'm using vue.js in this app and I tried importing the js file as an es6 module something like this:

import fx from './money.js';
export default {
// lots of code here..
}

I also tried including it as a JS module something like this

<script src="js/money.js"></script>

still i get an

[Vue warn]: Error in render: "fx error"
found in PlegeOffer.vue

and

fx error
or something like that

This library is how to use in the end, did not understand

javascript

fx.base = "USD";
fx.rates = {
"EUR" : 0.9499, // eg. 1 USD === 0.9499 EUR
"GBP" : 0.8143,
"CNY" : 6.9176,
"HKD" : 7.7554,
"JPY" : 116.91,
"KRW" : 1201,
"USD" : 1, // always include the base rate (1:1)
/* etc */
}

HTML

I would like to list the values of these currencies
For example, the default is 100USD, the value listed in other currencies

Doesn't work in Internet Explorer 8 and 9

Hello,

For some reason, the script works fine in Chrome, Safari, Firefox and IE 10. But IE 8 and 9 both results in 'unknown fx error'.

Does this script not work with IE 8 and 9?

Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.