Skip to content

Format to at least N decimal places #260

@jackc

Description

@jackc

It is sometimes convenient when working with money to always format to at least N decimal places, but not to round if there is more precision present. For example, US currency generally should be formatted to two decimal places, but if there are fractions of a cent they should be included not rounded:

(new BigNumber("1")).toFormat(2) // 1.00 - toFormat(2) will work correctly without fractions of a cent
(new BigNumber("1.234")).toFormat(2) // 1.23 - toFormat(2) loses fractional cents

I currently work around this as follows:

export const formatMinDP = function(n, dp) {
  const a = n.toFormat(dp)
  const b = n.toFormat()
  if (a.length > b.length) {
    return a
  } else {
    return b
  }
}

But it seems this would a common enough use that it might be useful to have built-in. Not sure what sort of interface would make sense. Maybe a no-op rounding mode or a new format key to skip rounding.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions