Git Product home page Git Product logo

pretty-money's Introduction

THIS PROJECT IS DEPRECATED

Starting with Node 14, all currency values are formatted correctly. You can use the built-in Number.prototype.toLocaleString() method instead.

This project will not be developed any further.

pretty-money

Money With Wings emoji

A tiny currency formatting library for JavaScript.

  • Small. Dependency-free. ~500 bytes minified and gzipped. Controlled by Size Limit.
  • Functional. The function is automatically curried (think Ramda).
  • Flexible. It can be tweaked to present any modern currency.
import prettyMoney from "pretty-money";
let price = prettyMoney({ currency: "EUR" }, 10000); //=> "10000 EUR"

Works in any environment, be that Node.js or a browser. Try it yourself!

Install

pretty-money is available on NPM, so you can install it your usual way:

npm install pretty-money
# or
yarn add pretty-money

If you only need to use pretty-money on the client side, you can install the latest version with jsDelivr:

<script src="https://cdn.jsdelivr.net/npm/pretty-money@1/dist/pretty-money.umd.js"></script>

In modern browsers, you can use:

<script type="module">
  import prettyMoney from "https://cdn.jsdelivr.net/npm/pretty-money@1/dist/pretty-money.modern.js"
</script>

Usage

There are two ways to use pretty-money: traditional and functional.

Traditional way is to call the function with two parameters: the config object and the number you need to format:

const prettyDollarConfig = {
    currency: "$",
    position: "before",
    spaced: false,
    thousandsDelimiter: ","
}

const priceA = prettyMoney(prettyDollarConfig, 1234); //=> "$1,234"
const priceB = prettyMoney(prettyDollarConfig, 567.89); //=> "$567.89"

Functional way is to curry the function, i.e. to create a function with a set config and to later call it with only one parameter — the number to format:

const prettyEuro = prettyMoney({
    currency: "€",
    decimals: "fixed",
    decimalDelimiter: ",",
    thousandsDelimiter: "."
})

const priceA = prettyEuro(1234); //=> "1.234,00 €"
const priceB = prettyEuro(567.89); //=> "567,89 €"

You can read more about the available configuration parameters in the next section, Config.

Config

currency

Type: string
Default: ""

The string to be used as currency symbol.
It can be a respective sign (like "$"), currency code (like "GBP") or a word (like "peso").

decimalDelimiter

Type: string
Default: "."

The string that separates the integer and the fractional parts of the number.

maxDecimal

Type: number
Default: 2

The maximum number of decimal places allowed in the number.

minDecimal

Type: number
Default: 0

The minimum number of decimal places allowed in the number. Has no effect when decimals is set to "fixed".

decimals

Type: string
Values: "fixed", "fluid" or "minmax"
Default: "minmax"

Sets the strategy to calculate the amount of decimal places.

  • "fixed" — the amount of places will always stay at maxDecimal. minDecimal has no effect.
  • "fluid" — the amount of places will stay at any number between minDecimal and maxDecimal, in order not to have trailing zeros.
  • "minmax" — the amount of places will stay at maxDecimal unless it's possible to be at minDecimal without having trailing zeros.

position

Type: string
Values: "before" or "after"
Default: "after"

Sets the position of the currency symbol with respect to the number.

spaced

Type: boolean
Default: true

Sets whether there should be a space between the number and the currency symbol.

thousandsDelimiter

Type: string
Default: ""

A string that separates the thousands of the number.

Difference from toLocaleString

ECMAScript's Number has a method toLocaleString, which has a similar idea. It too can be used to format numbers as financial values, and it even has a lot of built-in locales. However, the output of it is different on different Node.js versions and browsers:

let price = (10000).toLocaleString("ru", {
    style: "currency",
    currency: "RUB"
});

console.log(price);
//=> "10 000,00 ₽"    in modern browsers
//=> "RUB 10,000.00"  in Node v12.13.0
//=> "RUB 10,000"     in Node v4.8.6

This can lead to unexpected output and difficulties in debugging.

While pretty-money doesn't have any locales built-in, it provides a flexible API, so that the end user can compose any currency formatting function they need.

let price = prettyMoney({
    currency: "₽",
    thousandsDelimiter: " "
}, 10000);

console.log(price);
//=> "10 000 ₽"       in every Node, in every browser

Development

If you want to improve pretty-money, create your own fork of it or just play around with the developer build, here's all you need to know:

  • yarn dev to start a dev server, which will automatically build the library after you change the source and output it to ./dist/
  • yarn build to build the production-ready minified version of the library and output it to ./dist/
  • yarn test to build the project and run all tests, which include:
    • yarn test:lint to check the code formatting with ESLint (this won't auto fix errors)
    • yarn test:unit to run the uvu unit tests and calculate coverage
    • yarn test:size to check the size

There are no peer dependencies and other extra requirements. Any help is welcome when it keeps things simple and small.

Licence

Copyright © 2020–2021 Nikita Karamov
Licenced under the MIT License.

pretty-money's People

Contributors

kytta avatar

Stargazers

Rossi Meacham avatar netop://ウエハ avatar Michael Demarais avatar Ariel Falduto avatar  avatar Ilya Alonov avatar

Watchers

 avatar  avatar

pretty-money's Issues

Empty values (e.g. `""`, `0`) are being formatted incorrectly

hey,

is it possible to format empty values to an exptected output?

Like

const prettyEuro = {
   currency: "€",
   position: "after",
   spaced: true,
   decimals: "fixed",
   maxDecimals: 2,
   thousandsDelimiter: ".",
   decimalDelimiter: ","
};   

console.log( prettyMoney(prettyEuro, "0");

to

0,00 €

and not

,0 €

Thanks in advance, Louis

Rewrite test cases

The current test cases fail to catch the errors (see #8, #10, #11), since those test cases weren't coded in. The task is to rewrite the test cases to catch them all!

Parse and normalize various input formats

Hey Nick,

is it possible to extend your script to parse input values like

156.456

grafik

or 156.456,47

grafik

or is there a already a way to specify the input format?

You can also reach me via Discord: louis12356#6260

Thanks in advance, Louis :)

minDecimals has no effect on integer numbers

Steps to reproduce:

  1. Create the following config: const p = prettyMoney({ minDecimals: 1 })
  2. Format a number: p(1000)

Expected:
Output to be "1000.0" (since the default mode is "minmax")

Actual:
Output is "1000"

Issue with negative decimal number without integer part

I am using the following code and it removes the integer part, the output should be -0,5 but it is -,5, is this correct? or could it be solved?

prettyMoney(
  {
    decimalDelimiter: ',',
    thousandsDelimiter: '.',
    minDecimal: 0,
    maxDecimal: 2,
  },
  -0.5
) // outputs: '-,50'

If you try it on your example page with the default configuration, the same thing happens 😢

Error when trying to `require('pretty-money')`

Apparently, UMD export is broken on this version.

JS code:

const prettyMoney = require('pretty-money');

Console output:

node:internal/modules/cjs/loader:1108
      throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath);
      ^

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: [PROJECT]/node_modules/pretty-money/dist/pretty-money.modern.js
require() of ES modules is not supported.
require() of [PROJECT]/node_modules/pretty-money/dist/pretty-money.modern.js from [PROJECT]/index.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename pretty-money.modern.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from [PROJECT]/node_modules/pretty-money/package.json.

    at new NodeError (node:internal/errors:329:5)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1108:13)
    at Module.load (node:internal/modules/cjs/loader:971:32)
    at Function.Module._load (node:internal/modules/cjs/loader:812:14)
    at Module.require (node:internal/modules/cjs/loader:995:19)
    at require (node:internal/modules/cjs/helpers:92:18)
    at Object.<anonymous> ([PROJECT]/index.js:4:21)
    at Module._compile (node:internal/modules/cjs/loader:1091:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1120:10)
    at Module.load (node:internal/modules/cjs/loader:971:32) {
  code: 'ERR_REQUIRE_ESM'
}

Apparently, it tries to require the '.modern.js' version instead of the '.umd.js'

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.