Improve number formatting to handle additional edge cases

This commit is contained in:
Andrew Kingston 2024-10-18 11:01:15 +01:00
parent 1509d7d650
commit a337197402
No known key found for this signature in database
2 changed files with 26 additions and 10 deletions

View File

@ -1,3 +1,7 @@
<script context="module">
const NumberFormatter = Intl.NumberFormat()
</script>
<script>
import TextCell from "./TextCell.svelte"
@ -9,6 +13,24 @@
const newValue = isNaN(float) ? null : float
onChange(newValue)
}
const formatNumber = value => {
const type = typeof value
if (type !== "string" && type !== "number") {
return ""
}
if (type === "string" && !value.trim().length) {
return ""
}
const res = NumberFormatter.format(value)
return res === "NaN" ? value : res
}
</script>
<TextCell {...$$props} onChange={numberOnChange} bind:api type="number" />
<TextCell
{...$$props}
onChange={numberOnChange}
bind:api
type="number"
format={formatNumber}
/>

View File

@ -1,7 +1,3 @@
<script context="module">
const NumberFormatter = Intl.NumberFormat()
</script>
<script>
import { onMount } from "svelte"
@ -11,11 +7,13 @@
export let type = "text"
export let readonly = false
export let api
export let format = null
let input
let active = false
$: editable = focused && !readonly
$: displayValue = format?.(value) ?? value ?? ""
const handleChange = e => {
onChange(e.target.value)
@ -56,11 +54,7 @@
{:else}
<div class="text-cell" class:number={type === "number"}>
<div class="value">
{#if type === "number"}
{NumberFormatter.format(value ?? "")}
{:else}
{value ?? ""}
{/if}
{displayValue}
</div>
</div>
{/if}