#Custom string number formatting like C#?

7 messages · Page 1 of 1 (latest)

calm quiver
#

Hi all, does anyone know of an active library that allows a C# style number formatting string to be used to format a number e.g. 0000,.## would format 123.455 to 0,123.45? I’m recreating some desktop functionality in a web app and would like the user to be able to input the same string to format displayed numbers, and I’d like to avoid writing a custom parser.

toxic star
#

i don't think there's a built-in method for that format specifically, but there will definitely be libraries for it, so you won't have to make your own

#

for example, numeraljs which i found by googling "js number format library"

calm quiver
#

NumeralJS appears to be abandoned (last commit 7 years ago), apparently Numbro is the spiritual successor but they don’t appear to support format strings like Numeral did.

#

Or Excel formatting, haven’t looked for that but that’d work too. I’ll have a look. d3-format looks like the best contender so far.

scenic forge
#

maybe this?

const formatter = new Intl.NumberFormat('en-US', {
  minimumIntegerDigits: 4,
  maximumFractionDigits: 2,
})

formatter.format(123.455) // => "0,123.46"
#

if you really wanted .45 for that input then at least some browsers support a roundingMode option, but it looks like the DOM types in TS 5.6 don't know about it