Refaktorisierungs-Optionen und Fix für Zahlen-Parsing
This commit is contained in:
@@ -79,7 +79,7 @@
|
||||
<div class="text-center sm:pt-6">
|
||||
<button type="button"
|
||||
@click="navigate(
|
||||
$el.dataset.swapUrl, prettyNumber(convert(prepareValue(inputValue))))"
|
||||
$el.dataset.swapUrl, prettyNumber(convert(parseNumber(inputValue))))"
|
||||
data-swap-url="/{{ .Params.to }}-in-{{ .Params.from }}/"
|
||||
class="inline-flex items-center text-sm
|
||||
font-medium text-primary
|
||||
@@ -145,7 +145,7 @@
|
||||
</label>
|
||||
<input type="text" id="result"
|
||||
disabled
|
||||
:value="prettyNumber(convert(prepareValue(inputValue)))"
|
||||
:value="prettyNumber(convert(parseNumber(inputValue)))"
|
||||
class="textinput mt-1 block w-full">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -44,32 +44,35 @@ function prettyNumber(num, minPrecision, maxPrecision) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a German number string.
|
||||
* Accepts both comma and dot as decimal separator.
|
||||
* @param {string} input
|
||||
* @returns {string} Normalized string with dot as decimal
|
||||
* Parses a number string for conversion.
|
||||
* Accepts both German (1.234,56) and US (1,234.56) notation.
|
||||
* The last dot or comma is always the decimal separator;
|
||||
* all preceding ones are treated as thousand separators and removed.
|
||||
* Invalid or empty input returns Decimal(0).
|
||||
* @param {string} input - User input from field
|
||||
* @returns {Decimal} Parsed Decimal value
|
||||
*/
|
||||
function parseNumber(input) {
|
||||
if (!input) return '0';
|
||||
const hasComma = input.indexOf(',') !== -1;
|
||||
const hasDot = input.indexOf('.') !== -1;
|
||||
if (hasComma && hasDot) {
|
||||
return input.replace(/\./g, '').replace(/,/g, '.') || '0';
|
||||
}
|
||||
return input.replace(/,/g, '.') || '0';
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepares input value for conversion.
|
||||
* Returns a Decimal, or 1 if input is empty.
|
||||
* @param {string} input - User input from field
|
||||
* @returns {Decimal} Prepared value
|
||||
*/
|
||||
function prepareValue(input) {
|
||||
if (!input || input.trim() === '') {
|
||||
return new Decimal(1);
|
||||
return new Decimal(0);
|
||||
}
|
||||
const trimmed = input.trim();
|
||||
const lastDot = trimmed.lastIndexOf('.');
|
||||
const lastComma = trimmed.lastIndexOf(',');
|
||||
const lastSep = Math.max(lastDot, lastComma);
|
||||
let normalized;
|
||||
if (lastSep === -1) {
|
||||
normalized = trimmed;
|
||||
} else {
|
||||
const beforeSep = trimmed.slice(0, lastSep).replace(/[.,]/g, '');
|
||||
const afterSep = trimmed.slice(lastSep + 1);
|
||||
normalized = beforeSep + '.' + afterSep;
|
||||
}
|
||||
try {
|
||||
return new Decimal(normalized);
|
||||
} catch (e) {
|
||||
return new Decimal(0);
|
||||
}
|
||||
return new Decimal(input.replace(/,/g, '.'));
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user