amount-formatter
v1.1.0
Published
Format amount to currency and currency to amount
Downloads
10
Maintainers
Readme
amount-formatter
A lightweight package to format amounts to currency format and convert back to numeric values.
Installation
npm install amount-formatteror if you use yarn:
yarn add amount-formatterFeatures
- Convert numbers to currency format
- Convert currency formatted strings to numeric values
Usage
currency()
Converts a number or string to currency format:
import { currency } from 'amount-formatter';
currency(1000); // "1,000.00"
currency('1000'); // "1,000.00"
currency('1,000'); // "1,000.00"
currency('1000.5'); // "1,000.50"
currency('$1,000.50'); // "1,000.50"
currency(''); // ""
currency(undefined); // ""
currency(null); // ""
currency(); // ""You can optionally truncate decimals and add currency symbols:
currency(123.4567, { truncate: 2 }); // "123.45"
currency(123.4567, { truncate: 0 }); // "123"
currency(123.4567, { truncate: 4 }); // "123.4567"double()
Converts a currency formatted string to a number:
import { double } from 'amount-formatter';
double(1000); // 1000
double('1000'); // 1000
double('1,000'); // 1000
double('$1,000.50'); // 1000.5API
currency(value: number | string, options?: { truncate?: number }): string
Formats a number or string to currency format.
Parameters:
value: The value to format. Can be a number or a string.options: Optional parameter to control formatting:truncate: Number of decimals to truncate to.
Returns:
- A string in currency format (e.g., "1,000.00").
double(value: number | string): number
Converts a currency formatted string to a number.
Parameters:
value: The value to convert. Can be a number or a string.
Returns:
- A number.
Examples
import { currency, double } from 'amount-formatter';
// Format a number to currency
const price = 1234.5;
const formattedPrice = currency(price);
console.log(formattedPrice); // "1,234.50"
// Convert a string to number
const priceString = '$1,234.50';
const numberPrice = double(priceString);
console.log(numberPrice); // 1234.5
// Format a string that already has currency format
console.log(currency('$1,234.50')); // "1,234.50"Compatibility
This package works in:
- Node.js
- Modern browsers
License
MIT
