所以德國(guó)十進(jìn)制數(shù)使用十進(jìn)制逗號(hào)。格式化時(shí),我們也會(huì)使用句點(diǎn)對(duì)數(shù)字進(jìn)行分組。因此數(shù)字 10000.45 將被格式化為 10.000,45。
現(xiàn)在我想要一個(gè)輸入欄位(數(shù)字或文字),您可以在其中使用句點(diǎn)和逗號(hào)輸入「德語(yǔ)」方式。但是,我還想追蹤 JavaScript 中的「正?!箶?shù)值。
使用以下指令可以輕鬆將數(shù)值轉(zhuǎn)換為德語(yǔ)格式的值
number.toLocaleString("de-DE", { maxFractionDigits: 2 })
但是如何將其恢復(fù)為十進(jìn)制數(shù)呢?因?yàn)楫?dāng)我顯示像“7,20”這樣的德語(yǔ)格式的值時(shí),我會(huì)附加到末尾,對(duì)嗎?
這是一個(gè) svelte-repl 的初步嘗試,如下所示: https://svelte.dev/repl/fabd0a80f4ee49509cd875c0175bcf22?version=4.0.1
<script> let numericValue = 0; let formattedValue = ''; function formatNumber(value) { return value.toLocaleString("de", { minimumFractionDigits: 2, maximumFractionDigits: 2 }); } function handleInput(event) { // Remove dots as thousand separators and convert decimal comma to dot const inputValue = event.target.value.replace(/\./g, '').replace(/,/g, '.'); // Update numericValue with parsed float numericValue = parseFloat(inputValue); // Update formattedValue for display formattedValue = formatNumber(numericValue); } </script> <input type="text" value={formattedValue} on:input={handleInput} /> <p>Numeric value: {numericValue}</p>
理想情況下,我希望在輸入事件上顯示格式化的值。但它也可以出現(xiàn)在 on-change 事件上?;蛏踔潦褂门赃叺陌粹o或其他東西。 如果有任何提示,我將不勝感激! :)
我建議不要弄亂用戶(hù)輸入,也就是不要在 input
事件處理程序中設(shè)定 formattedValue
。如果您想很好地設(shè)定數(shù)字格式,請(qǐng)?jiān)诘谝淮物@示元件時(shí)執(zhí)行此操作,並在模糊
上執(zhí)行此操作,以防止幹?jǐn)_使用者的意圖。
如果您確實(shí)想在使用者輸入時(shí)嚴(yán)格規(guī)定某種格式,那麼這並不簡(jiǎn)單,因?yàn)楸仨毧紤]遊標(biāo)位置、數(shù)字符號(hào)、清除值和其他因素。還有一些函式庫(kù)可以實(shí)現(xiàn)這一點(diǎn),例如imask
。