@@ -57,33 +57,8 @@ function getCurrencyDividerAndDecimal(divider: CurrencyDivider | undefined) {
5757 } ;
5858}
5959
60- function removeAllDotsAndCommas ( value : string ) : string {
61- return value . replace ( / [ , . ] / g, '' ) ;
62- }
63-
64- function iDontYetKnowWhatsGoingOnHere (
65- value : string ,
66- divider : CurrencyDivider ,
67- ) : string {
68- if ( value . length > 3 ) {
69- let arr : string [ ] = [ ] ;
70- for ( let i = 0 ; i < value . length ; i += 3 ) {
71- arr . push (
72- value
73- . split ( '' )
74- . splice ( value . length - i , 3 )
75- . join ( '' ) ,
76- ) ;
77- }
78-
79- arr = arr . reverse ( ) ;
80- arr . pop ( ) ;
81- let initial = arr . join ( '' ) ;
82- if ( value . includes ( initial ) ) {
83- value = value . replace ( initial , '' ) ;
84- }
85- return ( value = value + divider + arr . join ( divider ) ) ;
86- } else return value ;
60+ function convertToNumber ( value : string , divider : CurrencyDivider ) : number {
61+ return Number ( value . replace ( `/${ divider } /g` , '' ) ) ;
8762}
8863
8964export function getValueFromCurrencyMask ( {
@@ -96,33 +71,19 @@ export function getValueFromCurrencyMask({
9671
9772 if ( value . length >= newValue . length ) return undefined ;
9873
99- if ( newValue . includes ( decimal ) ) {
100- let intVal = removeAllDotsAndCommas ( newValue . split ( decimal ) [ 0 ] ) ;
101- let fractionalVal = newValue . split ( decimal ) [ 1 ] ;
102-
103- intVal = iDontYetKnowWhatsGoingOnHere ( intVal , divider ) ;
104-
105- newValue = intVal + decimal + fractionalVal ;
74+ const newValueAsNumber = convertToNumber ( newValue , divider ) ;
75+ let decimalPlaces : number =
76+ maxDecimalPlaces !== undefined ? maxDecimalPlaces : 2 ;
10677
107- let decimalPlaces : number =
108- maxDecimalPlaces !== undefined ? maxDecimalPlaces : 2 ;
109-
110- if (
111- newValue . split ( decimal ) [ 1 ] !== undefined &&
112- value . split ( decimal ) [ 1 ] !== undefined &&
113- newValue . split ( decimal ) [ 1 ] . length > value . split ( decimal ) [ 1 ] . length &&
114- value . split ( decimal ) [ 1 ] . length === decimalPlaces
115- ) {
116- return undefined ;
117- }
118- if ( newValue . split ( decimal ) [ 1 ] . length > decimalPlaces ) {
119- newValue = newValue . slice ( 0 , newValue . length - 1 ) ;
120- }
121- } else if ( newValue . length > 3 ) {
122- let arr : string [ ] = [ ] ;
123- let unmasked = removeAllDotsAndCommas ( newValue ) ;
124-
125- newValue = iDontYetKnowWhatsGoingOnHere ( unmasked , divider ) ;
78+ if ( divider === ',' ) {
79+ // en-US format: 123,456.00
80+ return newValueAsNumber . toLocaleString ( 'en-US' , {
81+ maximumFractionDigits : decimalPlaces ,
82+ } ) ;
83+ } else {
84+ // de-DE German uses comma as decimal separator and period for thousands
85+ return newValueAsNumber . toLocaleString ( 'de-DE' , {
86+ maximumFractionDigits : decimalPlaces ,
87+ } ) ;
12688 }
127- return newValue ;
12889}
0 commit comments