Giter Club home page Giter Club logo

parse-decimal-number's Introduction

parse-decimal-number Travis Coverage Status Downloads

FOSSA Status

Parse a decimal number with i18n format support (localized decimal points and thousands separators)

About

OK, let’s fix international numbers parsing and validation once and forever. I got the inspiration for this in a UI project because somehow the libraries we used didn’t do a great job, so I wrote my own parser, and this is a more polished version of it.

These are the design goals:

  • Simple. String in, float out, done. βœ“
  • Accurate. Parses numbers and returns NaN for non-numbers. (=good for input validation) βœ“
  • Lightweight. (<1k minified) βœ“
  • Complete. No external dependencies βœ“
  • Solid. 100% Code Coverage βœ“
  • CLDR Support. Supports cldr data βœ“

In it’s simplest form, you just use it as a parseFloat replacement.

Install

Install with npm

npm i parse-decimal-number --save

Usage

parseDecimalNumber = require('parse-decimal-number');
console.log(parseDecimalNumber('12,345,678.90'));
// -> 12345678.90

console.log(parseDecimalNumber('12.345.678,90','.,'));
// -> 12345678.90

parseDecimalNumber(string [,options])

Returns a float representation of string or NaN if string is not a parseable number. Use the optional options parameter to specify the thousands and decimal point characters.

Parameters

string A String that is supposed to contain a number.

options optional A string, array or hash with thousands and decimal separators.

  • String a two-character string consisting of the thousands character followed by the decimal point character, e.g. ',.'

  • Array An array of two elements, the first being the thousands character, the second being the decimal point character, e.g. ['.',',']

  • Hash with the following elements (this is compatible with NumeralJS)

    • thousands thousands separator character. Default: ,
    • decimal decimal point character. Default: .

enforceGroupSize A boolean indicating whether to support that individual groups between the thousands character are exactly 3 digits

Examples

console.log(parseDecimalNumber('12.345.678,90'));
// -> 12345678.90
String options
console.log(parseDecimalNumber('12.345.678,90','.,'));
// -> 12345678.90
Array options
console.log(parseDecimalNumber('12.345.678,90',['.',',']));
// -> 12345678.90
Hash options
var customSeparators = {thousands:'.',decimal:','};
console.log(parseDecimalNumber('12.345.678,90',customSeparators));
// -> 12345678.90

parseDecimalNumber.withOptions(options)

Returns a function that will take a string as an argument and return a float or NaN, just like parseDecimalNumber.

Example

  const cldr = require('cldr');

  const locale = 'de_DE';
  const options = cldr.extractNumberSymbols(locale);

  const parse = parseDecimalNumber.withOptions(options);

  parse('123.456.789,0123'); // -> 123456789.0123

Setting and Resetting Default Options

parseDecimalNumber.setOptions

Set the default thousands and decimal characters that are used when no options are passed to parseDecimalNumber.

var defaultSeparators = {thousands:'.',decimal:','};
parseDecimalNumber.setOptions(defaultSeparators);

console.log(parseDecimalNumber('12.345.678,90'));
// -> 12345678.90
parseDecimalNumber.factorySettings

has the same effect as parseDecimalNumber.setOptions({thousands:',',decimal:'.'};)

Using with cldr

You can easily apply CLDR data using the cldr package:

  const cldr = require('cldr');

  parseDecimalNumber(
    '12.345.678,90',
    cldr.extractNumberSymbols('de_DE')
  );

Using with Numeral.js

Numeral.js is good at formatting numbers and comes with an extensive set of locale data that you can use with parse-decimal-number.

If you use numeral in your project, you can use their locale data as follows:

parseDecimalNumber('12.345.678,90', numeral.localeData('de').delimiters);
// -> 12345678.9

You can of course use the same data to set the default values for parse-decimal-number:

parseDecimalNumber.setOptions(numeral.localeData('de').delimiters);
parseDecimalNumber('12.345.678,90');
// -> 12345678.9

Done ☺️

Related Projects

To keep this project as small and modular as possible, the locale data itself has been left out of this library. If you need locale date, other projects might be helpful:

Running tests

{%= include("tests") %}

Contributing

In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality, and please re-build the documentation with gulp-verb before submitting a pull request.

Author

Andreas Pizsa (http://github.com/AndreasPizsa)

License

Copyright (c) 2017 Andreas Pizsa (http://github.com/AndreasPizsa), contributors.

FOSSA Status Greenkeeper badge

parse-decimal-number's People

Contributors

andreaspizsa avatar atilacamurca avatar brentropy avatar daveywood avatar fossabot avatar greenkeeper[bot] avatar jacekk avatar renovate[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

parse-decimal-number's Issues

Dependency on node.js

The description says it's complete and it has no dependencies, but it looks like it's using Module from node.js. This leads to errors if node.js isn't part of your project.

Add Locale Data

Get data from a standards database, then create super compact structure with gulp, like

# locales.coffee
'.,dedeDEdeAT ,fr,.enenUK -kz'.match /([^a-z])([^a-z])(?:([a-z]{2}([A-Z]{2})?)+/

should be <1k for all countries/languages

Then do parseDecimalNumber('123 456 789,0','fr')

Introduce guessLocalesFromDecimalNumber(string)?

Parse Decimal number without thousands delimiter

Current Behavior (US Number format)

1,234,123.12 parses correctly and returns number 1234123.12

Expected Behavior

A option to turn the thousands delimiter off and have:
1,234,123.12 not be able to parse and return NaN.

License issue

@AndreasPizsa I checked license file, it's MIT license, and I can see the icon of MIT license.
screen shot 2017-08-21 at 2 51 14 pm

But in readme, the license part: Copyright (c) 2017 Andreas Pizsa (http://github.com/AndreasPizsa), contributors.
Does this is typo? Or which license parse-decimal-number is? Please confirm.

Dependency deprecation warning: gulp-util (npm)

On registry https://registry.npmjs.org/, the "latest" version (v3.0.8) of dependency gulp-util has the following deprecation notice:

gulp-util is deprecated - replace it, following the guidelines at https://medium.com/gulpjs/gulp-util-ca3b1f9f9ac5

Marking the latest version of an npm package as deprecated results in the entire package being considered deprecated, so contact the package author you think this is a mistake.

Affected package file(s): package.json

If you don't care about this, you can close this issue and not be warned about gulp-util's deprecation again. If you would like to completely disable all future deprecation warnings then add the following to your config:

"suppressNotifications": ["deprecationWarningIssues"]

Dependency deprecation warning: coffee-script (npm)

On registry https://registry.npmjs.org/, the "latest" version (v1.12.7) of dependency coffee-script has the following deprecation notice:

CoffeeScript on NPM has moved to "coffeescript" (no hyphen)

Marking the latest version of an npm package as deprecated results in the entire package being considered deprecated, so contact the package author you think this is a mistake.

Affected package file(s): package.json

If you don't care about this, you can close this issue and not be warned about coffee-script's deprecation again. If you would like to completely disable all future deprecation warnings then add the following to your config:

"suppressNotifications": ["deprecationWarningIssues"]

Dependency deprecation warning: gulp-uglifyjs (npm)

On registry https://registry.npmjs.org/, the "latest" version (v0.6.2) of dependency gulp-uglifyjs has the following deprecation notice:

Since gulp-sourcemaps now works, use gulp-uglify instead

Marking the latest version of an npm package as deprecated results in the entire package being considered deprecated, so contact the package author you think this is a mistake.

Affected package file(s): package.json

If you don't care about this, you can close this issue and not be warned about gulp-uglifyjs's deprecation again. If you would like to completely disable all future deprecation warnings then add the following to your config:

"suppressNotifications": ["deprecationWarningIssues"]

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.