From d01cc769701145d9adb6419f37ab744f9bcb13a7 Mon Sep 17 00:00:00 2001 From: Paul Chavard Date: Mon, 23 Oct 2023 16:46:07 +0200 Subject: [PATCH] fix(decimal_champ): only remove dots if coma also present --- .../controllers/format_controller.ts | 31 ++++++++----------- spec/system/users/brouillon_spec.rb | 22 +++++++++++++ 2 files changed, 35 insertions(+), 18 deletions(-) diff --git a/app/javascript/controllers/format_controller.ts b/app/javascript/controllers/format_controller.ts index 8ae7ec1f8..d5712d46e 100644 --- a/app/javascript/controllers/format_controller.ts +++ b/app/javascript/controllers/format_controller.ts @@ -52,12 +52,19 @@ export class FormatController extends ApplicationController { } private formatDecimal(value: string) { - const decimalSeparator = getDecimalSeparator(value); - const number = - decimalSeparator == ',' - ? value.replace(/\./g, '').replace(/,/g, '.') - : value.replace(/,/g, ''); - return number.replace(new RegExp(`[^-?\\d.]`, 'g'), ''); + let formattedNumber = value; + const lastDotIndex = value.lastIndexOf('.'); + const lastCommaIndex = value.lastIndexOf(','); + if (lastDotIndex != -1 && lastCommaIndex != -1) { + if (lastDotIndex < lastCommaIndex) { + formattedNumber = value.replace(/\./g, ''); + } else { + formattedNumber = value.replace(/,/g, ''); + } + } + return formattedNumber + .replace(/,/g, '.') + .replace(new RegExp(`[^-?\\d.]`, 'g'), ''); } } @@ -71,15 +78,3 @@ function replaceValue(target: HTMLInputElement, value: string) { target.selectionEnd = end ? end - delta : 0; target.selectionDirection = dir; } - -function getDecimalSeparator(value: string) { - if (value.indexOf('.') != -1 && value.indexOf(',') != -1) { - if (value.lastIndexOf('.') < value.lastIndexOf(',')) { - return ','; - } - return '.'; - } else if (value.indexOf(',') != -1) { - return ','; - } - return (1.1).toLocaleString().indexOf('.') != -1 ? '.' : ','; -} diff --git a/spec/system/users/brouillon_spec.rb b/spec/system/users/brouillon_spec.rb index 54a58526f..84b1c488e 100644 --- a/spec/system/users/brouillon_spec.rb +++ b/spec/system/users/brouillon_spec.rb @@ -205,6 +205,28 @@ describe 'The user' do wait_until { champ_value_for('nombre décimal') == '123456.78' } + champ_past_value_for('nombre décimal', '123 456,78') + wait_until { + champ_value_for('nombre décimal') == '123456.78' + } + + fill_in('nombre décimal', with: '123 456.78') + wait_until { + champ_value_for('nombre décimal') == '123456.78' + } + champ_past_value_for('nombre décimal', '123 456.78') + wait_until { + champ_value_for('nombre décimal') == '123456.78' + } + + fill_in('nombre décimal', with: '123 456.002') + wait_until { + champ_value_for('nombre décimal') == '123456.002' + } + fill_in('nombre décimal', with: '123 456,002') + wait_until { + champ_value_for('nombre décimal') == '123456.002' + } champ_past_value_for('nombre décimal', '1,234.56') wait_until {