smirzaei / currency-formatter Goto Github PK
View Code? Open in Web Editor NEW[NOT ACTIVELY MAINTAINED] A simple Javascript utility that helps you to display currency properly
License: MIT License
[NOT ACTIVELY MAINTAINED] A simple Javascript utility that helps you to display currency properly
License: MIT License
Hi, great script!
It would be useful to be able to set global options for each currency such as to not use a decimal place. Is this possible?
Many thanks
The Array.prototype.find is part of ECMA 2015. Mozilla also provudes a polyfill for non supported browsers.
This will nake the library smaller.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
this 0.0.x
versioning if very annoying to deal with :)
I absolutely love this repo. Thanks for creating it!
The one thing It's missing for me is the name of the currency which I use when the user is selecting their currency from a menu. I've pulled in the names from this gist which is fine but adding it to the repo will make things much cleaner.
Thanks again and keep up the good work!
Everything seems to be ES5 except the use of an error function
line 16:
var currency = data.find(c => c.code === options.code) || this.defaultCurrency;
line 42:
return data.find(c => c.code === currencyCode);
Hello,
after reading the first lines of the project page, I started substituting currency-formatter usages in my project with Intl, but I'm afraid that the world is not ready for this.
Problems arised when I tried to use it-IT as a locale for some currencies: I use Docker and node 10.10.0-alpine doesn't ship with full-icu (and I find it more than correct, since hardly full-icu would be used) so I would need to install it.
As reported here
nodejs/node#19214
having full-icu working seems to increase the binary size of 14M and I can't find a way to install only the locales I want: reading Intl documentation on Nodejs page seems that the only option to have currency formatting managing locales different than os ones is to install full-icu
https://nodejs.org/api/intl.html
I'm unsure if adopting Intl instead of currency-formatter is a good option when build size matters.
Any opinion is more than welcomed
Last but not least: my aim is to have a certain symbol as decimal separator and a certain other one as thousands separator. I'm not interested in sticking to a particular locale
Hi, my app failed upon update today, it seems due to upgrading to 1.0.5 - when I call
currencyFormatter.format(0, 'GBP')
I get the type error of cannot find 'replace' of undefined.
Rolled back to 1.0.4 and it is fine
'BTC' not correct
'XBT' correct
Is it possible to extend the number of currency supported via code?
I want to override the default setting for a currency so that I can provide space between symbol and number while setting the currency as USD. currency it comes from the currencies.json file and we can not override it.
Hi there,
I realize this is no longer maintained but I was curious if you would take a pull request to update the currencies.json file.
Also, can you share where you sourced these values from previously? I have been searching for a good source of the "decimal" and "thousandths" separators but haven't had any luck as of yet.
Thanks for your time!
This commit introduces a polyfill which doesn't play nicely with Repos which use CoffeeScript.
In particular, using of
in CoffeeScript is turns into an in
in Javascript which loops over keys you don't own.
I noticed when formatting BHD
(Bahraini dinar) that it doesn't follow the template you set up. Is this because RTL languages are set up to be the opposite in the format?
In the currencies.json
file, symbolOnLeft
is marked as true
, however the symbol displays on the right when formatting.
If I change the currency file to have an alphanumeric symbol for BHD
such as BD
it displays correctly. I'm guessing this is because Arabic is written from right to left, so the symbol is naturally trying to position itself on the right instead of the left.
Hi! good utility!
You have some mistakes, for example symbol of KZT
.
I have database of currency (only official symbols)
You can just take it or use plugin. Also i can send PR after couple of days.
Seems like the formatter doesn't handle negative values, below example prints out "$-10.00".
var currencyFormatter = require('currency-formatter');
console.log(currencyFormatter.format(-10.0, { code: 'USD' })); // prints $-10.00
Is there an option that I will need to set or negative values are not supported?
This prevents to have a new line between amount and symbol. As the lib is for dislay purpose, not for calculation purpose, it shouldn't be a problem for users.
Maybe an additional 'global setting' could be used.
Thanks for the lib btw.
Hey :)
It would be nice to have the accounting.unformat function here.
I don't want to import your lib and import your library your are using
Hi,
the german local should also use the point as a thousand seperator. But the implementation is only showing a blank.
As a workaround I am using the netherland locale...
(Both should be the same)
Current Implementation of 1,000,000.00: --> 1 000 000,00 €
Correct german usage: 1.000.000,00 €
With kind regards!
The mapping between a locale and the currency is done case-insensitively, but the mapping between a locale and its locale format is done case sensitively. This can cause a locale's currency to be recognized, but not the formatting, if the user is not careful.
> currency.format("1234.56", { locale: 'en-ie' });
'1 234,56 €'
> currency.format("1234.56", { locale: 'en-IE' });
'€ 1,234.56'
What about if add those currencies ?
I'm testing my application, and I have included some tests that cover the behaviour managed by currency-formatter
, and I'm having the following issue:
I have been digging a little bit into the problem by buffering the received value and the expected value, and I found out that there's a difference between both elements:
As you can see, there's a difference between the received value and the expected value. I have checked out the string encoding in each case, and under a certain circumstance, it's coded as windows-1251
. To reproduce this error, you have to call the format
method with the following configuration:
format(6500, {
code: 'EUR',
locale: 'es-ES',
precision: 0
})
This is the test I created to check out if it's failing or not:
it('Returns 6.500 € for es-ES, EUR and precision 0', () => {
var result = currencyFormatter.format(6500, {
code: 'EUR',
locale: 'es-ES',
precision: 0
})
assert.equal(result, '6.500 €')
})
Indeed there's something wrong, but I'm not sure if it's in the format function or in the accounting.formatMoney
function that is called on it.
Let me know if you need more information to reproduce the error.
Any chance of a browser build for the package?
So that we could directly use it in a browser using a <script>
tag.
I know there is an Internationalization API for the currency formatting but I opted for this plugin because it does the required job that I needed in my project. It handles currency decimal points very well and also allows to give symbol option as null which was the requirement.
It is working very well but I got to know there is one problem in the currency json file.
IQD currency code which is of country Iraq is having the wrong decimalDigits value in currencies.json file.
IQD decimalDigits should be 3 but in the file it is specified 2.
It would be helpful if you update the file.
Is there a reason for the library to convert
currencyFormatter.format(0.999, { code: 'EUR'})
shows "1,00 €"
Is there a reason for this rounding off, and also is there a way to avoid this rounding off ?
@smirzaei already hinted that it might be a good idea to do a full rewrite of this library. I've been thinking a bit, and I'd like to share some of my thoughts of what I think would be good to include in a rewrite.
Perhaps we could use this issue as a place to discuss, and as a central place to monitor the progress of these issues once we start implementing them.
Not code-specific, but perhaps worth discussing:
We've already had a bit of a discussion regarding the purpose of this library in #30. I think it might be a good idea to formulate the purpose of this library, and the problem scope it takes on. My attempt:
Thinking of our library in this context helps us constrain the use cases that we want to support. For example, we currently go through a bit of effort to export the list of currencies as an array. I don't think we should do this. IMHO we should expose each format we have, but leave it up to users to wrap it into one big array if they want to.
Would involve setting up babel, since modules should provide an ES5 compatible version.
I think we might want to revise the data structure of our formats. As @Gwened pointed out in #37, a currency can have different formats, even within a single country:
For example, I think Canadians speaking French will use 5$ while English speakers write $5.
In a similar way, if I'm targeting brits traveling in Europe, I would write €5 instead of 5 €.
I think it might be a good idea to split our formatting data up into currency, and locale formatting. Where currency data is (surprise) specified per currency, while locale formatting data should perhaps be specified per language ('en', 'es', 'de', ...etc) or even per locale ('en-US', 'en-GB', 'de-DE', 'de-AT', ...etc). These currency and locale formats could look like this:
Currency:
{
code: 'USD',
symbol: '$',
decimalDigits: 2
defaultLocale: 'en-US'
}
Locale:
{
locale: 'en-US',
thousandsSeparator: ' ',
decimalSeparator: '.',
symbolOnLeft: false,
spaceBetweenAmountAndSymbol: true,
}
We could map the current list of currencies to these two types of files. A nice benefit that comes with this structure would be that a lot of redundant formatting data can be captured in "language" level formats ('en', 'de') as opposed to duplicating all of the number formatting information. For example; 85 currencies share the exact same values as USD
for thousandsSeparator
, decimalSeparator
, symbolOnLeft
, and decimalDigits
:
Object.values(currencies).filter(c => (
c.thousandsSeparator === ',' &&
c.decimalSeparator === '.' &&
c.symbolOnLeft === true &&
c.decimalDigits === 2).length
))
// > 85
We could just write a single formatting file with locale: 'en'
and set defaultLocale: 'en'
for all of these 85 currencies.
As requested in #34.
I personally think this will be the most important, as well as the most challenging feature. I've recently gone through the process of optimizing the performance of my own app, and stripping unused code is the first place to start. Allowing users to whitelist currencies would be a straightforward way to reduce the amount of unused bytes.
To make this happen we need to split formatting data into separate files, and provide a way for users to add currency and locale formatting data. (As a side note, we should probably have a convenience build or entrypoint which contains all formatting data.)
I'm a fan of how react-intl
does this:
import {addLocaleData} from 'react-intl';
import en from 'react-intl/locale-data/en';
import fr from 'react-intl/locale-data/fr';
import es from 'react-intl/locale-data/es';
addLocaleData([...en, ...fr, ...es]);
If we end up splitting currency and locale data, we would need two functions; addCurrencyData
and addLocaleData
. Given the defaultLocale
, we could have currency files auto-import their default locale. This would result in a simpler API for users that don't care about locale formatting (they'll never have to call addLocaleData
). Downside; if you only need to support a small set of locales, but all currencies, we might end up importing a lot of locale formats which will never be used.
Things to discuss:
var number = 123456.789;
currencyFormatter.format(123456.789, { code: 'INR' });
// this displays, "123,456.79₹" but should be, "1,23,456.789₹".
Is there a setting to adjust commas?
It happens that including all the currencies adds up 30K in a webpage (against ~2K for the lib itself).
It is useful when the currency value is dynamic and not predictable.
Although in some (many?) cases, the list of currencies is deterministic. When you use only one or two currencies, the cost of including the lib should not be higher than 3KB.
import formatEUR from 'currency-formatter/EUR'
formatEUR(30.9); // --> '30,90€'
Internally, it means that currency-formatter/EUR.js
could look like:
import currency from '../currencies/EUR.json';
import format from '../index.js';
const formatCurrency = format.bind(null, currency);
export default formatCurrency;
By extent, maybe the first and last argument could be swapped to allow partial application, which is also a good way to support a functional approach:
import format from 'currency-formatter';
const formatEUR = format.bind(null, { currency: 'EUR' });
formatEUR(30.9); // --> '30,90€'
#PossiblyOverEngineering
cc @DavidBruant
Very useful library, thanks for sharing!
So this is a major pain in the ass, and not specific to this library at all, but placement of the euro sign (€) differs between countries.
Quote from the European commission:
Where should the euro symbol be placed: ‘€ 100’ or ‘100 €’?
There are no official standards on where to place the euro symbol. In English text, the usual practice is to place the symbol "€" before the amount in figures, i.e. € 100. In French text, the symbol is usually placed after the amount in figures, i.e. 100 €.
The app I'm working on requires correct placement across locales, so for example, our Dutch version should display €100
, while the French version should display 100 €
.
Currently we maintain our own list of currencies per country, which means that we have two "versions" of the euro, one with symbolOnLeft=true
and the other one with symbolOnLeft=false
. I can hardly imagine we're the only ones struggling with this, and this library might be a nice central place to solve this issue.
Would love to hear your thoughts!
If the symbol is on right and the space is added, should the space be added to the left of the symbol ?
12.20CHF should be 12.20 CHF
?
Said I would raise this for awareness.
We had this formatting issue internally and was going to look into using an external module, but it seems to be commonly overlooked.
My worked company is an FX&Payment company, and we used this module for some internal projects.
Since I noticed that [NOT ACTIVELY MAINTAINED]
in the project title.
So, I'm glad to help maintain this module :)
Version used:
"currency-formatter": "^1.3.2"
My function accepts a number and changes it to USD. Since I don't want decimal values, so I have specified the decimal option as zero.
export default (amount) => { return currencyFormatter.format(20,{code: currency, decimal: 0}); }
The expected output should be $20
But the output comes as $20000
Similarly, if I write the code like this
export default (amount) => { return currencyFormatter.format(20,{code: currency, decimal: 1}); }
The result comes as ---- $20100
Version used:
"currency-formatter": "^1.4.3"
Hello, I would like to report about a bug. When I try to change the currency of the value 0, the result is undefined.
consolecurrencyFormatter.format(0, { locale: 'en-US' });
//=> undefined
When should be for example:
consolecurrencyFormatter.format(0, { locale: 'en-US' });
// => '$0'
consolecurrencyFormatter.format(0, { locale: 'de-DE' });
//=> '0 €'
Thank you so much.
Did your formatter built in JS by Mozilla?
The function name are absolutely same. I surprised.
Line 37 in c5bebdb
should be:
precision: typeof options.precision === 'number' ? options.precision : currency.decimalDigits
and the same with the other options
It would be nice if there was a option to remove zero cents, but leave cents if there was a value.
30 > $30
12.43 > $12.43
12.43543 > $12.43543
12.0000 > $12
If I have the string $2,000.00
that was formatted by currency-formatter, is it possible to remove formatting and return it to a pure Number?
In this instance I would love to return 2000.00
.
I've been using this in a small application for a few months, on a new deployment I found it doesn't work anymore.
I'm getting issues with currencies.json and localeFormats.json
ERROR in ./~/currency-formatter/currencies.json
Module parse failed: /node_modules/currency-formatter/currencies.json Unexpected token (2:6)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (2:6)
ERROR in ./~/currency-formatter/localeFormats.json
Module parse failed: /node_modules/currency-formatter/localeFormats.json Unexpected token (2:8)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (2:8)
The issues seem to have come about since a few pull requests were merged at the start of Feb.
Any ideas?
makes it difficult to do import { format } from 'currency-formatter'
It seems this lib only allows one format per currency.
However, the format, in particular symbolOnLeft, usually depends on the locale.
For example, I think Canadians speaking French will use 5$ while English speakers write $5.
In a similar way, if I'm targeting brits traveling in Europe, I would write €5 instead of 5 €.
Is there something I'm missing?
Where did you get the data? I'd like for it to be exposed so I can use it outside this library as well.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.