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> <script>
import TextCell from "./TextCell.svelte" import TextCell from "./TextCell.svelte"
@ -9,6 +13,24 @@
const newValue = isNaN(float) ? null : float const newValue = isNaN(float) ? null : float
onChange(newValue) 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> </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> <script>
import { onMount } from "svelte" import { onMount } from "svelte"
@ -11,11 +7,13 @@
export let type = "text" export let type = "text"
export let readonly = false export let readonly = false
export let api export let api
export let format = null
let input let input
let active = false let active = false
$: editable = focused && !readonly $: editable = focused && !readonly
$: displayValue = format?.(value) ?? value ?? ""
const handleChange = e => { const handleChange = e => {
onChange(e.target.value) onChange(e.target.value)
@ -56,11 +54,7 @@
{:else} {:else}
<div class="text-cell" class:number={type === "number"}> <div class="text-cell" class:number={type === "number"}>
<div class="value"> <div class="value">
{#if type === "number"} {displayValue}
{NumberFormatter.format(value ?? "")}
{:else}
{value ?? ""}
{/if}
</div> </div>
</div> </div>
{/if} {/if}