Formateo de numeros en JS
This commit is contained in:
@ -0,0 +1,72 @@
|
||||
@push('page_scripts')
|
||||
<script>
|
||||
class NumberInput {
|
||||
input
|
||||
isRational
|
||||
outputLocale
|
||||
currentValue
|
||||
formatters
|
||||
|
||||
constructor({input, isRational, outputLocale}) {
|
||||
this.input = input
|
||||
this.isRational = isRational
|
||||
this.outputLocale = outputLocale
|
||||
|
||||
this.formatters = {}
|
||||
const locales = ['es-CL', 'en-US']
|
||||
locales.forEach(locale => {
|
||||
this.formatters[locale] = {
|
||||
rational: new Intl.NumberFormat(locale, {minimumFractionDigits: 2, maximumFractionDigits: 2}),
|
||||
integer: new Intl.NumberFormat(locale)
|
||||
}
|
||||
})
|
||||
|
||||
if (this.input.value !== '') {
|
||||
this.currentValue = this.process(this.input.value)
|
||||
}
|
||||
}
|
||||
watch() {
|
||||
this.input.addEventListener('change', event => {
|
||||
const value = this.process(event.target.value)
|
||||
this.currentValue = value
|
||||
this.input.value = this.format(value)
|
||||
})
|
||||
}
|
||||
process(stringValue) {
|
||||
if (stringValue === '') {
|
||||
return ''
|
||||
}
|
||||
if (typeof stringValue !== 'string') {
|
||||
return stringValue
|
||||
}
|
||||
return this.formatters[this.detectLocale(stringValue)][this.isRational ? 'rational' : 'integer'].parse(stringValue)
|
||||
}
|
||||
detectLocale(stringValue) {
|
||||
if (stringValue === '') {
|
||||
return ''
|
||||
}
|
||||
if (typeof stringValue !== 'string') {
|
||||
return stringValue
|
||||
}
|
||||
const outputFormat = this.formatters[this.outputLocale][this.isRational ? 'rational' : 'integer'].isLocale(stringValue)
|
||||
const otherFormats = Object.entries(this.formatters).filter(formatter => formatter[0] !== this.outputLocale).map(formatter => {
|
||||
return {
|
||||
locale: formatter[0],
|
||||
value: formatter[1][this.isRational ? 'rational' : 'integer'].isLocale(stringValue)
|
||||
}
|
||||
}).filter(formatter => formatter.value)
|
||||
|
||||
if (outputFormat) {
|
||||
return this.outputLocale
|
||||
}
|
||||
if (otherFormats.length > 0) {
|
||||
return otherFormats[0].locale
|
||||
}
|
||||
return 'en-US'
|
||||
}
|
||||
format(value) {
|
||||
return this.formatters[this.outputLocale][this.isRational ? 'rational' : 'integer'].format(value)
|
||||
}
|
||||
}
|
||||
</script>
|
||||
@endpush
|
Reference in New Issue
Block a user