/
dinero.js.html
1056 lines (993 loc) · 43.2 KB
/
dinero.js.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>
dinero.js - Documentation
</title>
<link href="https://www.braintreepayments.com/images/favicon-ccda0b14.png" rel="icon" type="image/png">
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.7.0/highlight.min.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
<link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/docsearch.js/2/docsearch.min.css" />
<script type="text/javascript" src="https://cdn.jsdelivr.net/docsearch.js/2/docsearch.min.js"></script>
<!-- start Mixpanel -->
<script type="text/javascript">(function(e,a){if(!a.__SV){var b=window;try{var c,l,i,j=b.location,g=j.hash;c=function(a,b){return(l=a.match(RegExp(b+"=([^&]*)")))?l[1]:null};g&&c(g,"state")&&(i=JSON.parse(decodeURIComponent(c(g,"state"))),"mpeditor"===i.action&&(b.sessionStorage.setItem("_mpcehash",g),history.replaceState(i.desiredHash||"",e.title,j.pathname+j.search)))}catch(m){}var k,h;window.mixpanel=a;a._i=[];a.init=function(b,c,f){function e(b,a){var c=a.split(".");2==c.length&&(b=b[c[0]],a=c[1]);b[a]=function(){b.push([a].concat(Array.prototype.slice.call(arguments,
0)))}}var d=a;"undefined"!==typeof f?d=a[f]=[]:f="mixpanel";d.people=d.people||[];d.toString=function(b){var a="mixpanel";"mixpanel"!==f&&(a+="."+f);b||(a+=" (stub)");return a};d.people.toString=function(){return d.toString(1)+".people (stub)"};k="disable time_event track track_pageview track_links track_forms register register_once alias unregister identify name_tag set_config reset people.set people.set_once people.increment people.append people.union people.track_charge people.clear_charges people.delete_user".split(" ");
for(h=0;h<k.length;h++)e(d,k[h]);a._i.push([b,c,f])};a.__SV=1.2;b=e.createElement("script");b.type="text/javascript";b.async=!0;b.src="undefined"!==typeof MIXPANEL_CUSTOM_LIB_URL?MIXPANEL_CUSTOM_LIB_URL:"file:"===e.location.protocol&&"//cdn.mxpnl.com/libs/mixpanel-2-latest.min.js".match(/^\/\//)?"https://cdn.mxpnl.com/libs/mixpanel-2-latest.min.js":"//cdn.mxpnl.com/libs/mixpanel-2-latest.min.js";c=e.getElementsByTagName("script")[0];c.parentNode.insertBefore(b,c)}})(document,window.mixpanel||[]);
mixpanel.init("1919205b2da72e4da3b9b6639b444d59");</script>
<!-- end Mixpanel -->
</head>
<body>
<svg style="display: none;">
<defs>
<symbol id="linkIcon" fill="#706d77" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg">
<path d="M0 0h24v24H0z" fill="none"/>
<path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71 0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71 0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76 0 5-2.24 5-5s-2.24-5-5-5z"/>
</symbol>
</defs>
</svg>
<input type="checkbox" id="nav-trigger" class="nav-trigger" />
<label for="nav-trigger" class="navicon-button x">
<div class="navicon"></div>
</label>
<label for="nav-trigger" class="overlay"></label>
<div class="top-nav-wrapper">
<ul>
<li >
<a href="index.html">
<svg fill="#6D6D6D" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg">
<path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z"/>
<path d="M0 0h24v24H0z" fill="none"/>
</svg>
</a>
</li>
<li>
<div class="search-wrapper">
<svg fill="#6D6D6D" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg">
<path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"/>
<path d="M0 0h24v24H0z" fill="none"/>
</svg>
<input type="text" placeholder="Search" class="search-input">
</div>
</li>
</ul>
</div>
<nav>
<h3 class="reference-title">
Dinero.js
</h3>
<h3>Modules</h3><ul><li id="Dinero-nav"><a href="module-Dinero.html">Dinero</a><ul class='methods'><li data-type="method" id="Dinero-getAmount-nav"><a href="module-Dinero.html#~getAmount">getAmount</a></li><li data-type="method" id="Dinero-getCurrency-nav"><a href="module-Dinero.html#~getCurrency">getCurrency</a></li><li data-type="method" id="Dinero-getLocale-nav"><a href="module-Dinero.html#~getLocale">getLocale</a></li><li data-type="method" id="Dinero-setLocale-nav"><a href="module-Dinero.html#~setLocale">setLocale</a></li><li data-type="method" id="Dinero-getPrecision-nav"><a href="module-Dinero.html#~getPrecision">getPrecision</a></li><li data-type="method" id="Dinero-convertPrecision-nav"><a href="module-Dinero.html#~convertPrecision">convertPrecision</a></li><li data-type="method" id="Dinero-add-nav"><a href="module-Dinero.html#~add">add</a></li><li data-type="method" id="Dinero-subtract-nav"><a href="module-Dinero.html#~subtract">subtract</a></li><li data-type="method" id="Dinero-multiply-nav"><a href="module-Dinero.html#~multiply">multiply</a></li><li data-type="method" id="Dinero-divide-nav"><a href="module-Dinero.html#~divide">divide</a></li><li data-type="method" id="Dinero-percentage-nav"><a href="module-Dinero.html#~percentage">percentage</a></li><li data-type="method" id="Dinero-allocate-nav"><a href="module-Dinero.html#~allocate">allocate</a></li><li data-type="method" id="Dinero-convert-nav"><a href="module-Dinero.html#~convert">convert</a></li><li data-type="method" id="Dinero-equalsTo-nav"><a href="module-Dinero.html#~equalsTo">equalsTo</a></li><li data-type="method" id="Dinero-lessThan-nav"><a href="module-Dinero.html#~lessThan">lessThan</a></li><li data-type="method" id="Dinero-lessThanOrEqual-nav"><a href="module-Dinero.html#~lessThanOrEqual">lessThanOrEqual</a></li><li data-type="method" id="Dinero-greaterThan-nav"><a href="module-Dinero.html#~greaterThan">greaterThan</a></li><li data-type="method" id="Dinero-greaterThanOrEqual-nav"><a href="module-Dinero.html#~greaterThanOrEqual">greaterThanOrEqual</a></li><li data-type="method" id="Dinero-isZero-nav"><a href="module-Dinero.html#~isZero">isZero</a></li><li data-type="method" id="Dinero-isPositive-nav"><a href="module-Dinero.html#~isPositive">isPositive</a></li><li data-type="method" id="Dinero-isNegative-nav"><a href="module-Dinero.html#~isNegative">isNegative</a></li><li data-type="method" id="Dinero-hasSubUnits-nav"><a href="module-Dinero.html#~hasSubUnits">hasSubUnits</a></li><li data-type="method" id="Dinero-hasCents-nav"><a href="module-Dinero.html#~hasCents">hasCents</a></li><li data-type="method" id="Dinero-hasSameCurrency-nav"><a href="module-Dinero.html#~hasSameCurrency">hasSameCurrency</a></li><li data-type="method" id="Dinero-hasSameAmount-nav"><a href="module-Dinero.html#~hasSameAmount">hasSameAmount</a></li><li data-type="method" id="Dinero-toFormat-nav"><a href="module-Dinero.html#~toFormat">toFormat</a></li><li data-type="method" id="Dinero-toUnit-nav"><a href="module-Dinero.html#~toUnit">toUnit</a></li><li data-type="method" id="Dinero-toRoundedUnit-nav"><a href="module-Dinero.html#~toRoundedUnit">toRoundedUnit</a></li><li data-type="method" id="Dinero-toObject-nav"><a href="module-Dinero.html#~toObject">toObject</a></li><li data-type="method" id="Dinero-toJSON-nav"><a href="module-Dinero.html#~toJSON">toJSON</a></li><li data-type="method" id="Dinero-normalizePrecision-nav"><a href="module-Dinero.html#.normalizePrecision">normalizePrecision</a></li></ul></li></ul><h3 id="global-nav">Global</h3><ul><li><a href="global.html#Defaults">Defaults</a></li><li><a href="global.html#Globals">Globals</a></li></ul>
</nav>
<div id="main">
<a href="https://github.com/sarahdayan/dinero.js" target="_blank">
<img style="position: fixed; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png" alt="Fork me on GitHub">
</a>
<h1 class="page-title">
dinero.js
</h1>
<section>
<article>
<pre class="prettyprint source linenums"><code>import { Defaults, Globals } from './services/settings'
import Static from './services/static'
import Format from './services/format'
import Calculator from './services/calculator'
import CurrencyConverter from './services/currency-converter'
import {
assert,
assertPercentage,
assertValidRatios,
assertInteger
} from './services/assert'
import { isUndefined } from './services/helpers'
const calculator = Calculator()
/**
* A Dinero object is an immutable data structure representing a specific monetary value.
* It comes with methods for creating, parsing, manipulating, testing, transforming and formatting them.
*
* A Dinero object has:
*
* * An `amount`, expressed in minor currency units.
* * A `currency`, expressed as an {@link https://en.wikipedia.org/wiki/ISO_4217#Active_codes ISO 4217 currency code}.
* * A `precision`, expressed as an integer, to represent the number of decimal places in the `amount`.
* This is helpful when you want to represent fractional minor currency units (e.g.: $10.4545).
* You can also use it to represent a currency with a different [exponent](https://en.wikipedia.org/wiki/ISO_4217#Treatment_of_minor_currency_units_.28the_.22exponent.22.29) than `2` (e.g.: Iraqi dinar with 1000 fils in 1 dinar (exponent of `3`), Japanese yen with no sub-units (exponent of `0`)).
* * An optional `locale` property that affects how output strings are formatted.
*
* Here's an overview of the public API:
*
* * **Access:** {@link module:Dinero~getAmount getAmount}, {@link module:Dinero~getCurrency getCurrency}, {@link module:Dinero~getLocale getLocale} and {@link module:Dinero~getPrecision getPrecision}.
* * **Manipulation:** {@link module:Dinero~add add}, {@link module:Dinero~subtract subtract}, {@link module:Dinero~multiply multiply}, {@link module:Dinero~divide divide}, {@link module:Dinero~percentage percentage}, {@link module:Dinero~allocate allocate} and {@link module:Dinero~convert convert}.
* * **Testing:** {@link module:Dinero~equalsTo equalsTo}, {@link module:Dinero~lessThan lessThan}, {@link module:Dinero~lessThanOrEqual lessThanOrEqual}, {@link module:Dinero~greaterThan greaterThan}, {@link module:Dinero~greaterThanOrEqual greaterThanOrEqual}, {@link module:Dinero~isZero isZero}, {@link module:Dinero~isPositive isPositive}, {@link module:Dinero~isNegative isNegative}, {@link module:Dinero~hasSubUnits hasSubUnits}, {@link module:Dinero~hasSameCurrency hasSameCurrency} and {@link module:Dinero~hasSameAmount hasSameAmount}.
* * **Configuration:** {@link module:Dinero~setLocale setLocale}.
* * **Conversion & formatting:** {@link module:Dinero~toFormat toFormat}, {@link module:Dinero~toUnit toUnit}, {@link module:Dinero~toRoundedUnit toRoundedUnit}, {@link module:Dinero~toObject toObject}, {@link module:Dinero~toJSON toJSON}, {@link module:Dinero~convertPrecision convertPrecision} and {@link module:Dinero.normalizePrecision normalizePrecision}.
*
* @module Dinero
* @param {Number} [options.amount=0] - The amount in minor currency units (as an integer).
* @param {String} [options.currency='USD'] - An ISO 4217 currency code.
* @param {String} [options.precision=2] - The number of decimal places to represent.
*
* @throws {TypeError} If `amount` or `precision` is invalid.
*
* @return {Object}
*/
const Dinero = options => {
const { amount, currency, precision } = Object.assign(
{},
{
amount: Dinero.defaultAmount,
currency: Dinero.defaultCurrency,
precision: Dinero.defaultPrecision
},
options
)
assertInteger(amount)
assertInteger(precision)
const {
globalLocale,
globalFormat,
globalRoundingMode,
globalFormatRoundingMode
} = Dinero
const globalExchangeRatesApi = Object.assign(
{},
Dinero.globalExchangeRatesApi
)
/**
* Uses ES5 function notation so `this` can be passed through call, apply and bind
* @ignore
*/
const create = function(options) {
const obj = Object.assign(
{},
Object.assign({}, { amount, currency, precision }, options),
Object.assign({}, { locale: this.locale }, options)
)
return Object.assign(
Dinero({
amount: obj.amount,
currency: obj.currency,
precision: obj.precision
}),
{
locale: obj.locale
}
)
}
/**
* Uses ES5 function notation so `this` can be passed through call, apply and bind
* @ignore
*/
const assertSameCurrency = function(comparator) {
assert(
this.hasSameCurrency(comparator),
new TypeError(
'You must provide a Dinero instance with the same currency.'
)
)
}
return {
/**
* Returns the amount.
*
* @example
* // returns 500
* Dinero({ amount: 500 }).getAmount()
*
* @return {Number}
*/
getAmount() {
return amount
},
/**
* Returns the currency.
*
* @example
* // returns 'EUR'
* Dinero({ currency: 'EUR' }).getCurrency()
*
* @return {String}
*/
getCurrency() {
return currency
},
/**
* Returns the locale.
*
* @example
* // returns 'fr-FR'
* Dinero().setLocale('fr-FR').getLocale()
*
* @return {String}
*/
getLocale() {
return this.locale || globalLocale
},
/**
* Returns a new Dinero object with an embedded locale.
*
* @param {String} newLocale - The new locale as an {@link http://tools.ietf.org/html/rfc5646 BCP 47 language tag}.
*
* @example
* // Returns a Dinero object with locale 'ja-JP'
* Dinero().setLocale('ja-JP')
*
* @return {Dinero}
*/
setLocale(newLocale) {
return create.call(this, { locale: newLocale })
},
/**
* Returns the precision.
*
* @example
* // returns 3
* Dinero({ precision: 3 }).getPrecision()
*
* @return {Number}
*/
getPrecision() {
return precision
},
/**
* Returns a new Dinero object with a new precision and a converted amount.
*
* By default, fractional minor currency units are rounded using the **half to even** rule ([banker's rounding](http://wiki.c2.com/?BankersRounding)).
* This can be necessary when you need to convert objects to a smaller precision.
*
* Rounding *can* lead to accuracy issues as you chain many times. Consider a minimal amount of subsequent conversions for safer results.
* You can also specify a different `roundingMode` to better fit your needs.
*
* @param {Number} newPrecision - The new precision.
* @param {String} [roundingMode='HALF_EVEN'] - The rounding mode to use: `'HALF_ODD'`, `'HALF_EVEN'`, `'HALF_UP'`, `'HALF_DOWN'`, `'HALF_TOWARDS_ZERO'` or `'HALF_AWAY_FROM_ZERO'`.
*
* @example
* // Returns a Dinero object with precision 3 and amount 1000
* Dinero({ amount: 100, precision: 2 }).convertPrecision(3)
*
* @throws {TypeError} If `newPrecision` is invalid.
*
* @return {Dinero}
*/
convertPrecision(newPrecision, roundingMode = globalFormatRoundingMode) {
assertInteger(newPrecision)
return create.call(this, {
amount: calculator.round(
calculator.multiply(
this.getAmount(),
Math.pow(10, calculator.subtract(newPrecision, this.getPrecision()))
),
roundingMode
),
precision: newPrecision
})
},
/**
* Returns a new Dinero object that represents the sum of this and an other Dinero object.
*
* If Dinero objects have a different `precision`, they will be first converted to the highest.
*
* @param {Dinero} addend - The Dinero object to add.
*
* @example
* // returns a Dinero object with amount 600
* Dinero({ amount: 400 }).add(Dinero({ amount: 200 }))
* @example
* // returns a Dinero object with amount 144545 and precision 4
* Dinero({ amount: 400 }).add(Dinero({ amount: 104545, precision: 4 }))
*
* @throws {TypeError} If `addend` has a different currency.
*
* @return {Dinero}
*/
add(addend) {
assertSameCurrency.call(this, addend)
const addends = Dinero.normalizePrecision([this, addend])
return create.call(this, {
amount: calculator.add(addends[0].getAmount(), addends[1].getAmount()),
precision: addends[0].getPrecision()
})
},
/**
* Returns a new Dinero object that represents the difference of this and an other Dinero object.
*
* If Dinero objects have a different `precision`, they will be first converted to the highest.
*
* @param {Dinero} subtrahend - The Dinero object to subtract.
*
* @example
* // returns a Dinero object with amount 200
* Dinero({ amount: 400 }).subtract(Dinero({ amount: 200 }))
* @example
* // returns a Dinero object with amount 64545 and precision 4
* Dinero({ amount: 104545, precision: 4 }).subtract(Dinero({ amount: 400 }))
*
* @throws {TypeError} If `subtrahend` has a different currency.
*
* @return {Dinero}
*/
subtract(subtrahend) {
assertSameCurrency.call(this, subtrahend)
const subtrahends = Dinero.normalizePrecision([this, subtrahend])
return create.call(this, {
amount: calculator.subtract(
subtrahends[0].getAmount(),
subtrahends[1].getAmount()
),
precision: subtrahends[0].getPrecision()
})
},
/**
* Returns a new Dinero object that represents the multiplied value by the given factor.
*
* By default, fractional minor currency units are rounded using the **half to even** rule ([banker's rounding](http://wiki.c2.com/?BankersRounding)).
*
* Rounding *can* lead to accuracy issues as you chain many times. Consider a minimal amount of subsequent calculations for safer results.
* You can also specify a different `roundingMode` to better fit your needs.
*
* @param {Number} multiplier - The factor to multiply by.
* @param {String} [roundingMode='HALF_EVEN'] - The rounding mode to use: `'HALF_ODD'`, `'HALF_EVEN'`, `'HALF_UP'`, `'HALF_DOWN'`, `'HALF_TOWARDS_ZERO'` or `'HALF_AWAY_FROM_ZERO'`.
*
* @example
* // returns a Dinero object with amount 1600
* Dinero({ amount: 400 }).multiply(4)
* @example
* // returns a Dinero object with amount 800
* Dinero({ amount: 400 }).multiply(2.001)
* @example
* // returns a Dinero object with amount 801
* Dinero({ amount: 400 }).multiply(2.00125, 'HALF_UP')
*
* @return {Dinero}
*/
multiply(multiplier, roundingMode = globalRoundingMode) {
return create.call(this, {
amount: calculator.round(
calculator.multiply(this.getAmount(), multiplier),
roundingMode
)
})
},
/**
* Returns a new Dinero object that represents the divided value by the given factor.
*
* By default, fractional minor currency units are rounded using the **half to even** rule ([banker's rounding](http://wiki.c2.com/?BankersRounding)).
*
* Rounding *can* lead to accuracy issues as you chain many times. Consider a minimal amount of subsequent calculations for safer results.
* You can also specify a different `roundingMode` to better fit your needs.
*
* As rounding is applied, precision may be lost in the process. If you want to accurately split a Dinero object, use {@link module:Dinero~allocate allocate} instead.
*
* @param {Number} divisor - The factor to divide by.
* @param {String} [roundingMode='HALF_EVEN'] - The rounding mode to use: `'HALF_ODD'`, `'HALF_EVEN'`, `'HALF_UP'`, `'HALF_DOWN'`, `'HALF_TOWARDS_ZERO'` or `'HALF_AWAY_FROM_ZERO'`.
*
* @example
* // returns a Dinero object with amount 100
* Dinero({ amount: 400 }).divide(4)
* @example
* // returns a Dinero object with amount 52
* Dinero({ amount: 105 }).divide(2)
* @example
* // returns a Dinero object with amount 53
* Dinero({ amount: 105 }).divide(2, 'HALF_UP')
*
* @return {Dinero}
*/
divide(divisor, roundingMode = globalRoundingMode) {
return create.call(this, {
amount: calculator.round(
calculator.divide(this.getAmount(), divisor),
roundingMode
)
})
},
/**
* Returns a new Dinero object that represents a percentage of this.
*
* As rounding is applied, precision may be lost in the process. If you want to accurately split a Dinero object, use {@link module:Dinero~allocate allocate} instead.
*
* @param {Number} percentage - The percentage to extract (between 0 and 100).
*
* @example
* // returns a Dinero object with amount 5000
* Dinero({ amount: 10000 }).percentage(50)
*
* @throws {RangeError} If `percentage` is out of range.
*
* @return {Dinero}
*/
percentage(percentage) {
assertPercentage(percentage)
return this.multiply(calculator.divide(percentage, 100))
},
/**
* Allocates the amount of a Dinero object according to a list of ratios.
*
* Sometimes you need to split monetary values but percentages can't cut it without adding or losing pennies.
* A good example is invoicing: let's say you need to bill $1,000.03 and you want a 50% downpayment.
* If you use {@link module:Dinero~percentage percentage}, you'll get an accurate Dinero object but the amount won't be billable: you can't split a penny.
* If you round it, you'll bill a penny extra.
* With {@link module:Dinero~allocate allocate}, you can split a monetary amount then distribute the remainder as evenly as possible.
*
* You can use percentage style or ratio style for `ratios`: `[25, 75]` and `[1, 3]` will do the same thing.
*
* @param {Number[]} ratios - The ratios to allocate the money to.
*
* @example
* // returns an array of two Dinero objects
* // the first one with an amount of 502
* // the second one with an amount of 501
* Dinero({ amount: 1003 }).allocate([50, 50])
* @example
* // returns an array of two Dinero objects
* // the first one with an amount of 25
* // the second one with an amount of 75
* Dinero({ amount: 100 }).allocate([1, 3])
*
* @throws {TypeError} If ratios are invalid.
*
* @return {Dinero[]}
*/
allocate(ratios) {
assertValidRatios(ratios)
const total = ratios.reduce((a, b) => calculator.add(a, b))
let remainder = this.getAmount()
const shares = ratios.map(ratio => {
const share = Math.floor(
calculator.divide(calculator.multiply(this.getAmount(), ratio), total)
)
remainder = calculator.subtract(remainder, share)
return create.call(this, { amount: share })
})
for (let i = 0; remainder > 0; i++) {
shares[i] = shares[i].add(create.call(this, { amount: 1 }))
remainder = calculator.subtract(remainder, 1)
}
return shares
},
/**
* Returns a Promise containing a new Dinero object converted to another currency.
*
* You must provide your own API to retrieve exchange rates. This method won't work if you don't set either {@link Globals global API parameters}, or local ones for your instance.
*
* Here are some exchange rate APIs you can use:
*
* * [Fixer](https://fixer.io)
* * [Open Exchange Rates](https://openexchangerates.org)
* * [Coinbase](https://api.coinbase.com/v2/exchange-rates)
* * More [foreign](https://github.com/toddmotto/public-apis#currency-exchange) and [crypto](https://github.com/toddmotto/public-apis#cryptocurrency) exchange rate APIs.
*
* You will need to specify at least:
*
* * a **destination currency**: the currency in which you want to convert your Dinero object. You can specify it with `currency`.
* * an **endpoint**: the API URL to query exchange rates, with parameters. You can specify it with `options.endpoint`.
* * a **property path**: the path to access the wanted rate in your API's JSON response. For example, with a response of:
* ```json
* {
* "data": {
* "base": "USD",
* "destination": "EUR",
* "rate": "0.827728919"
* }
* }
* ```
* Then the property path is `'data.rate'`. You can specify it with `options.propertyPath`.
*
* The base currency (the currency of your Dinero object) and the destination currency can be used as "merge tags" with the mustache syntax, respectively `{{from}}` and `{{to}}`.
* You can use these tags to refer to these values in `options.endpoint` and `options.propertyPath`.
*
* For example, if you need to specify the base currency as a query parameter, you can do the following:
*
* ```js
* {
* endpoint: 'https://yourexchangerates.api/latest?base={{from}}'
* }
* ```
*
* @param {String} currency - The destination currency, expressed as an {@link https://en.wikipedia.org/wiki/ISO_4217#Active_codes ISO 4217 currency code}.
* @param {String} options.endpoint - The API endpoint to retrieve exchange rates.
* @param {String} options.propertyPath - The property path to the rate.
* @param {Object} [options.headers] - The HTTP headers to provide, if needed.
* @param {String} [options.roundingMode='HALF_EVEN'] - The rounding mode to use: `'HALF_ODD'`, `'HALF_EVEN'`, `'HALF_UP'`, `'HALF_DOWN'`, `'HALF_TOWARDS_ZERO'` or `'HALF_AWAY_FROM_ZERO'`.
*
* @example
* // your global API parameters
* Dinero.globalExchangeRatesApi = { ... }
*
* // returns a Promise containing a Dinero object with the destination currency
* // and the initial amount converted to the new currency.
* Dinero({ amount: 500 }).convert('EUR')
* @example
* // returns a Promise containing a Dinero object,
* // with specific API parameters and rounding mode for this specific instance.
* Dinero({ amount: 500 })
* .convert('XBT', {
* endpoint: 'https://yourexchangerates.api/latest?base={{from}}',
* propertyPath: 'data.rates.{{to}}',
* headers: {
* 'user-key': 'xxxxxxxxx'
* },
* roundingMode: 'HALF_UP'
* })
* @example
* // usage with Promise.prototype.then and Promise.prototype.catch
* Dinero({ amount: 500 })
* .convert('EUR')
* .then(dinero => {
* dinero.getCurrency() // returns 'EUR'
* })
* .catch(err => {
* // handle errors
* })
* @example
* // usage with async/await
* (async () => {
* const price = await Dinero({ amount: 500 }).convert('EUR')
* price.getCurrency() // returns 'EUR'
* })()
*
* @return {Promise}
*/
convert(currency, options) {
options = Object.assign({}, globalExchangeRatesApi, options)
return CurrencyConverter(options)
.getExchangeRate(this.getCurrency(), currency)
.then(rate => {
assert(
!isUndefined(rate),
new TypeError(
`No rate was found for the destination currency "${currency}".`
)
)
return create.call(this, {
amount: calculator.round(
calculator.multiply(this.getAmount(), parseFloat(rate)),
options.roundingMode
),
currency
})
})
},
/**
* Checks whether the value represented by this object equals to the other.
*
* @param {Dinero} comparator - The Dinero object to compare to.
*
* @example
* // returns true
* Dinero({ amount: 500, currency: 'EUR' }).equalsTo(Dinero({ amount: 500, currency: 'EUR' }))
* @example
* // returns false
* Dinero({ amount: 500, currency: 'EUR' }).equalsTo(Dinero({ amount: 800, currency: 'EUR' }))
* @example
* // returns false
* Dinero({ amount: 500, currency: 'USD' }).equalsTo(Dinero({ amount: 500, currency: 'EUR' }))
* @example
* // returns false
* Dinero({ amount: 500, currency: 'USD' }).equalsTo(Dinero({ amount: 800, currency: 'EUR' }))
* @example
* // returns true
* Dinero({ amount: 1000, currency: 'EUR', precision: 2 }).equalsTo(Dinero({ amount: 10000, currency: 'EUR', precision: 3 }))
* @example
* // returns false
* Dinero({ amount: 10000, currency: 'EUR', precision: 2 }).equalsTo(Dinero({ amount: 10000, currency: 'EUR', precision: 3 }))
*
* @return {Boolean}
*/
equalsTo(comparator) {
return this.hasSameAmount(comparator) && this.hasSameCurrency(comparator)
},
/**
* Checks whether the value represented by this object is less than the other.
*
* @param {Dinero} comparator - The Dinero object to compare to.
*
* @example
* // returns true
* Dinero({ amount: 500 }).lessThan(Dinero({ amount: 800 }))
* @example
* // returns false
* Dinero({ amount: 800 }).lessThan(Dinero({ amount: 500 }))
* @example
* // returns true
* Dinero({ amount: 5000, precision: 3 }).lessThan(Dinero({ amount: 800 }))
* @example
* // returns false
* Dinero({ amount: 800 }).lessThan(Dinero({ amount: 5000, precision: 3 }))
*
* @throws {TypeError} If `comparator` has a different currency.
*
* @return {Boolean}
*/
lessThan(comparator) {
assertSameCurrency.call(this, comparator)
const comparators = Dinero.normalizePrecision([this, comparator])
return comparators[0].getAmount() < comparators[1].getAmount()
},
/**
* Checks whether the value represented by this object is less than or equal to the other.
*
* @param {Dinero} comparator - The Dinero object to compare to.
*
* @example
* // returns true
* Dinero({ amount: 500 }).lessThanOrEqual(Dinero({ amount: 800 }))
* @example
* // returns true
* Dinero({ amount: 500 }).lessThanOrEqual(Dinero({ amount: 500 }))
* @example
* // returns false
* Dinero({ amount: 500 }).lessThanOrEqual(Dinero({ amount: 300 }))
* @example
* // returns true
* Dinero({ amount: 5000, precision: 3 }).lessThanOrEqual(Dinero({ amount: 800 }))
* @example
* // returns true
* Dinero({ amount: 5000, precision: 3 }).lessThanOrEqual(Dinero({ amount: 500 }))
* @example
* // returns false
* Dinero({ amount: 800 }).lessThanOrEqual(Dinero({ amount: 5000, precision: 3 }))
*
* @throws {TypeError} If `comparator` has a different currency.
*
* @return {Boolean}
*/
lessThanOrEqual(comparator) {
assertSameCurrency.call(this, comparator)
const comparators = Dinero.normalizePrecision([this, comparator])
return comparators[0].getAmount() <= comparators[1].getAmount()
},
/**
* Checks whether the value represented by this object is greater than the other.
*
* @param {Dinero} comparator - The Dinero object to compare to.
*
* @example
* // returns false
* Dinero({ amount: 500 }).greaterThan(Dinero({ amount: 800 }))
* @example
* // returns true
* Dinero({ amount: 800 }).greaterThan(Dinero({ amount: 500 }))
* @example
* // returns true
* Dinero({ amount: 800 }).greaterThan(Dinero({ amount: 5000, precision: 3 }))
* @example
* // returns false
* Dinero({ amount: 5000, precision: 3 }).greaterThan(Dinero({ amount: 800 }))
*
* @throws {TypeError} If `comparator` has a different currency.
*
* @return {Boolean}
*/
greaterThan(comparator) {
assertSameCurrency.call(this, comparator)
const comparators = Dinero.normalizePrecision([this, comparator])
return comparators[0].getAmount() > comparators[1].getAmount()
},
/**
* Checks whether the value represented by this object is greater than or equal to the other.
*
* @param {Dinero} comparator - The Dinero object to compare to.
*
* @example
* // returns true
* Dinero({ amount: 500 }).greaterThanOrEqual(Dinero({ amount: 300 }))
* @example
* // returns true
* Dinero({ amount: 500 }).greaterThanOrEqual(Dinero({ amount: 500 }))
* @example
* // returns false
* Dinero({ amount: 500 }).greaterThanOrEqual(Dinero({ amount: 800 }))
* @example
* // returns true
* Dinero({ amount: 800 }).greaterThanOrEqual(Dinero({ amount: 5000, precision: 3 }))
* @example
* // returns true
* Dinero({ amount: 500 }).greaterThanOrEqual(Dinero({ amount: 5000, precision: 3 }))
* @example
* // returns false
* Dinero({ amount: 5000, precision: 3 }).greaterThanOrEqual(Dinero({ amount: 800 }))
*
* @throws {TypeError} If `comparator` has a different currency.
*
* @return {Boolean}
*/
greaterThanOrEqual(comparator) {
assertSameCurrency.call(this, comparator)
const comparators = Dinero.normalizePrecision([this, comparator])
return comparators[0].getAmount() >= comparators[1].getAmount()
},
/**
* Checks if the value represented by this object is zero.
*
* @example
* // returns true
* Dinero({ amount: 0 }).isZero()
* @example
* // returns false
* Dinero({ amount: 100 }).isZero()
*
* @return {Boolean}
*/
isZero() {
return this.getAmount() === 0
},
/**
* Checks if the value represented by this object is positive.
*
* @example
* // returns false
* Dinero({ amount: -10 }).isPositive()
* @example
* // returns true
* Dinero({ amount: 10 }).isPositive()
* @example
* // returns true
* Dinero({ amount: 0 }).isPositive()
*
* @return {Boolean}
*/
isPositive() {
return this.getAmount() >= 0
},
/**
* Checks if the value represented by this object is negative.
*
* @example
* // returns true
* Dinero({ amount: -10 }).isNegative()
* @example
* // returns false
* Dinero({ amount: 10 }).isNegative()
* @example
* // returns false
* Dinero({ amount: 0 }).isNegative()
*
* @return {Boolean}
*/
isNegative() {
return this.getAmount() < 0
},
/**
* Checks if this has minor currency units.
* Deprecates {@link module:Dinero~hasCents hasCents}.
*
* @example
* // returns false
* Dinero({ amount: 1100 }).hasSubUnits()
* @example
* // returns true
* Dinero({ amount: 1150 }).hasSubUnits()
*
* @return {Boolean}
*/
hasSubUnits() {
return calculator.modulo(this.getAmount(), Math.pow(10, precision)) !== 0
},
/**
* Checks if this has minor currency units.
*
* @deprecated since version 1.4.0, will be removed in 2.0.0
* Use {@link module:Dinero~hasSubUnits hasSubUnits} instead.
*
* @example
* // returns false
* Dinero({ amount: 1100 }).hasCents()
* @example
* // returns true
* Dinero({ amount: 1150 }).hasCents()
*
* @return {Boolean}
*/
hasCents() {
return calculator.modulo(this.getAmount(), Math.pow(10, precision)) !== 0
},
/**
* Checks whether the currency represented by this object equals to the other.
*
* @param {Dinero} comparator - The Dinero object to compare to.
*
* @example
* // returns true
* Dinero({ amount: 2000, currency: 'EUR' }).hasSameCurrency(Dinero({ amount: 1000, currency: 'EUR' }))
* @example
* // returns false
* Dinero({ amount: 1000, currency: 'EUR' }).hasSameCurrency(Dinero({ amount: 1000, currency: 'USD' }))
*
* @return {Boolean}
*/
hasSameCurrency(comparator) {
return this.getCurrency() === comparator.getCurrency()
},
/**
* Checks whether the amount represented by this object equals to the other.
*
* @param {Dinero} comparator - The Dinero object to compare to.
*
* @example
* // returns true
* Dinero({ amount: 1000, currency: 'EUR' }).hasSameAmount(Dinero({ amount: 1000 }))
* @example
* // returns false
* Dinero({ amount: 2000, currency: 'EUR' }).hasSameAmount(Dinero({ amount: 1000, currency: 'EUR' }))
* @example
* // returns true
* Dinero({ amount: 1000, currency: 'EUR', precision: 2 }).hasSameAmount(Dinero({ amount: 10000, precision: 3 }))
* @example
* // returns false
* Dinero({ amount: 10000, currency: 'EUR', precision: 2 }).hasSameAmount(Dinero({ amount: 10000, precision: 3 }))
*
* @return {Boolean}
*/
hasSameAmount(comparator) {
const comparators = Dinero.normalizePrecision([this, comparator])
return comparators[0].getAmount() === comparators[1].getAmount()
},
/**
* Returns this object formatted as a string.
*
* The format is a mask which defines how the output string will be formatted.
* It defines whether to display a currency, in what format, how many fraction digits to display and whether to use grouping separators.
* The output is formatted according to the applying locale.
*
* Object | Format | String
* :--------------------------- | :---------------- | :---
* `Dinero({ amount: 500050 })` | `'$0,0.00'` | $5,000.50
* `Dinero({ amount: 500050 })` | `'$0,0'` | $5,001
* `Dinero({ amount: 500050 })` | `'$0'` | $5001
* `Dinero({ amount: 500050 })` | `'$0.0'` | $5000.5
* `Dinero({ amount: 500050 })` | `'USD0,0.0'` | USD5,000.5
* `Dinero({ amount: 500050 })` | `'0,0.0 dollar'` | 5,000.5 dollars
*
* Don't try to substitute the `$` sign or the `USD` code with your target currency, nor adapt the format string to the exact format you want.
* The format is a mask which defines a pattern and returns a valid, localized currency string.
* If you want to display the object in a custom way, either use {@link module:Dinero~getAmount getAmount}, {@link module:Dinero~toUnit toUnit} or {@link module:Dinero~toRoundedUnit toRoundedUnit} and manipulate the output string as you wish.
*
* {@link module:Dinero~toFormat toFormat} wraps around `Number.prototype.toLocaleString`. For that reason, **format will vary depending on how it's implemented in the end user's environment**.
*
* You can also use `toLocaleString` directly:
* `Dinero().toRoundedUnit(digits, roundingMode).toLocaleString(locale, options)`.
*
* By default, amounts are rounded using the **half away from zero** rule ([commercial rounding](https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero)).
* You can also specify a different `roundingMode` to better fit your needs.
*
* @param {String} [format='$0,0.00'] - The format mask to format to.
* @param {String} [roundingMode='HALF_AWAY_FROM_ZERO'] - The rounding mode to use: `'HALF_ODD'`, `'HALF_EVEN'`, `'HALF_UP'`, `'HALF_DOWN'`, `'HALF_TOWARDS_ZERO'` or `'HALF_AWAY_FROM_ZERO'`.
*
* @example
* // returns $2,000
* Dinero({ amount: 200000 }).toFormat('$0,0')
* @example
* // returns €50.5
* Dinero({ amount: 5050, currency: 'EUR' }).toFormat('$0,0.0')
* @example
* // returns 100 euros
* Dinero({ amount: 10000, currency: 'EUR' }).setLocale('fr-FR').toFormat('0,0 dollar')
* @example
* // returns 2000
* Dinero({ amount: 200000, currency: 'EUR' }).toFormat()
* @example
* // returns $10
* Dinero({ amount: 1050 }).toFormat('$0', 'HALF_EVEN')
*
* @return {String}
*/
toFormat(format = globalFormat, roundingMode = globalFormatRoundingMode) {
const formatter = Format(format)
return this.toRoundedUnit(
formatter.getMinimumFractionDigits(),
roundingMode
).toLocaleString(this.getLocale(), {
currencyDisplay: formatter.getCurrencyDisplay(),
useGrouping: formatter.getUseGrouping(),
minimumFractionDigits: formatter.getMinimumFractionDigits(),
style: formatter.getStyle(),
currency: this.getCurrency()
})
},
/**
* Returns the amount represented by this object in units.
*
* @example
* // returns 10.5
* Dinero({ amount: 1050 }).toUnit()
* @example
* // returns 10.545
* Dinero({ amount: 10545, precision: 3 }).toUnit()
*
* @return {Number}
*/
toUnit() {
return calculator.divide(this.getAmount(), Math.pow(10, precision))
},
/**
* Returns the amount represented by this object in rounded units.
*
* By default, the method uses the **half away from zero** rule ([commercial rounding](https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero)).
* You can also specify a different `roundingMode` to better fit your needs.
*
* @example
* // returns 10.6
* Dinero({ amount: 1055 }).toRoundedUnit(1)
* @example
* // returns 10
* Dinero({ amount: 1050 }).toRoundedUnit(0, 'HALF_EVEN')
*
* @param {Number} digits - The number of fraction digits to round to.
* @param {String} [roundingMode='HALF_AWAY_FROM_ZERO'] - The rounding mode to use: `'HALF_ODD'`, `'HALF_EVEN'`, `'HALF_UP'`, `'HALF_DOWN'`, `'HALF_TOWARDS_ZERO'` or `'HALF_AWAY_FROM_ZERO'`.
*
* @return {Number}
*/
toRoundedUnit(digits, roundingMode = globalFormatRoundingMode) {
const factor = Math.pow(10, digits)
return calculator.divide(
calculator.round(
calculator.multiply(this.toUnit(), factor),
roundingMode
),
factor
)
},
/**
* Returns the object's data as an object literal.
*
* @example
* // returns { amount: 500, currency: 'EUR', precision: 2 }
* Dinero({ amount: 500, currency: 'EUR', precision: 2 }).toObject()
*
* @return {Object}
*/
toObject() {
return {
amount,
currency,
precision
}
},
/**
* Returns the object's data as an object literal.
*