Giter Site home page Giter Site logo

numeral-js's Introduction

A javascript library for formatting and manipulating numbers.

Website and documentation

Travis Build Status

Master Build Status

Develop Build Status

NPM

NPM

#CDNJS

CDNJS

Contributing

Important: Please create your branch from and submit pull requests to the develop branch. All pull requests must include the appropriate tests.

  1. Fork the library

  2. Install grunt

  3. Run npm install to install dependencies

  4. Create a new branch from develop

  5. Add your tests to the files in /tests

  6. To test your tests, run grunt

  7. When all your tests are passing, run grunt dist to compile and minify all files

  8. Submit a pull request to the develop branch.

Formats

Formats now exist in their own files and act more or less as plugins. Check out the bytes format for an example of how to create one.

Locales

When naming locale files use the ISO 639-1 language codes supplemented by ISO 3166-1 country codes when necessary.

Locale translations will not be merged without unit tests.

See the english unit tests for an example.

Changelog

2.0.6

Bug fix: Multi letter currency symbols and spacing

Added: Formatting of numbers with leading zeros

New format: Basic Point

Option: Added scalePercentBy100 (default: true) option to turn on/off scaling percentages

2.0.4

Bug fix: Incorrect abbreviations for values rounded up #187

Bug fix: Signed currency is inconsistent #89

2.0.2

Bug fix: Updated module definitions

2.0.1

Bug fix: Fixed regression for webpack/browserify/rollup

2.0.0

2.0.0 brings a lot of breaking changes and a reorganization of the repo, but also simplifies the api as well as the creating of custom formats.

Breaking change / Feature: All formats are now separate files. This makes it easy to create custom formats, and will also allow for custom builds with only certain formats. (Note: The built numeral.js still contains all formats in the repo).

Breaking change / Feature: All formats and locales are now loaded using numeral.register(type, name, {})

Breaking change: All language now renamed to locale and standardized to all lowercase filenames

Breaking change: The locale function no longer loads locales, it only sets the current locale

Breaking change: The unformat function has been removed numeral().unformat(string) and now happens on numeral init numeral(string)

Breaking change / Feature: Bytes are now formatted as: b (base 1000) and ib (base 1024)

Breaking change: numeral(NaN) is now treated the same as numeral(null) and no longer throws an error

Feature: Exponential format using e+ or e-

Bug fix: Update to floating point helpers (Note: Numeral does not fix JS floating point errors, but look to our tests to see that it covers quite a few cases.)

1.5.6

Bug fix: numeral converts strings to numbers

Bug fix: Null values return same as 0

1.5.5

Contained breaking changes, recommended to use 1.5.6

Bug fix: Switch bytes back to b and change iecBinary to ib, and calculate both using 1024 for backwards compatibility

1.5.4

Contained breaking changes, recommended to use 1.5.6

Tests: Changed all tests to use Mocha and Chai

Tests: Added browser tests for Chrome, Firefox, and IE using saucelabs

Added reset function to reset numeral to default options

Added nullFormat option

Update reduce polyfill

Added Binary bytes

Bug fix: Fixes problem with many optional decimals

1.5.3

Added currency symbol to optionally appear before negative sign / open paren

Added float precision math support

Added specification of abbreviation in thousands, millions, billions

1.5.2

Bug fix: Unformat should pass through if given a number

Added a mechanism to control rounding behaviour

Added languageData() for getting and setting language props at runtime

1.5.1

Bug fix: Make sure values aren't changed during formatting

1.5.0

Add defaultFormat(). numeral().format() uses the default to format if no string is provided

.unformat() returns 0 when passed no string

Added languages.js that contains all languages

Bug fix: Fix bug while unformatting ordinals

Add format option to always show signed value

Added ability to instantiate numeral with a string value of a number

1.4.9

Bug fix: Fix bug while unformatting ordinals

1.4.8

Bug fix: Throw error if language is not defined

1.4.7

Bug fix: Fix typo for trillion

1.4.6

Bug fix: remove ' from unformatting regex that was causing an error with fr-ch.js

1.4.5

Add zeroFormat() function that accepts a string for custom formating of zeros

Add valueOf() function

Chain functionality to language function

Make all minified files have the same .min.js filename ending

1.4.1

Bug fix: Bytes not formatting correctly

1.4.0

Add optional format for all decimals

1.3.4

Remove AMD module id. (This is encouraged by require.js to make the module more portable, and keep it from creating a global)

1.3.3

AMD define() compatibility.

1.3.2

Bug fix: Formatting some numbers results in the wrong value. Issue #21

1.3.1

Bug fix: Minor fix to unformatting parser

1.3.0

Add support for spaces before/after $, a, o, b in a format string

Bug fix: Fix unformat for languages that use '.' in ordinals

Bug fix: Fix round up floating numbers with no precision correctly.

Bug fix: Fix currency signs at the end in unformat

1.2.6

Add support for optional decimal places

1.2.5

Add support for appending currency symbol

1.2.4

Add support for humanized filesizes

1.2.3

Bug Fix: Fix unformatting for languages that use '.' as thousands delimiter

1.2.2

Changed language definition property 'money' to 'currency'

1.2.1

Bug fix: Fix unformatting non-negative abbreviations

1.2.0

Add language support

Update testing for to include languages

1.1.0

Add Tests

Bug fix: Fix difference returning negative values

1.0.4

Bug fix: Non negative numbers were displaying as negative when using parentheses

1.0.3

Add ordinal formatting using 'o' in the format

1.0.2

Add clone functionality

1.0.1

Added abbreviations for thousands and millions using 'a' in the format

1.0.0

Initial release

Acknowlegements

Numeral.js, while less complex, was inspired by and heavily borrowed from Moment.js

License

Numeral.js is freely distributable under the terms of the MIT license.

Copyright (c) 2012 Adam Draper

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

numeral-js's People

Contributors

adamwdraper avatar ammarhasan avatar apapirovski avatar atinux avatar azzlack avatar baer avatar clayzermk1 avatar daclayton avatar donvince avatar dresende avatar ecmel avatar godefroyo avatar hgarcia avatar jojosati avatar koesbong avatar lafriks avatar marcus-old avatar moeriki avatar mrcsabatoth avatar pbakondy avatar pdehaan avatar piefel avatar ragulka avatar rustybailey avatar samitheberber avatar shraymonks avatar sinky avatar ticking-clock avatar zeke avatar zeusdeux 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  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  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  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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

numeral-js's Issues

Numeral instantiated with non-numeric values return zero

This has probably not been changed as I'm expecting most are used to it defaulting to this behavior, but in my opinion, numeral('not a number') should definitely not evaluate to zero. Is there a particular reason that the top level parser sets something to a number right after ascertaining that it isn't numeric?

I'm not expecting the default behavior to change for this, but couldn't there be some sort of "tolerant" setting that can be optionally disabled?

Max/Min length padding

Currently there isn't anyway to easily pad a number. For instance if I want my percentages to be at least 3 numbers, so that they are all roughly the same length, there isn't a way to do that easily. '0.0%' will result in xx.x% and x.x%.

Document rounding behavior

Currently the docs say nothing about rounding, requiring experimentation (or browsing the source) to see what's going on.

Append currency symbol.

In some languages the currency symbol is after the number (price). Are you planing this feature ?

Signed currency is inconsistent

Using a format specifier with '$' and '+' produces inconsistent behavior:

numeral(-1000).format('$+0,0') === '-$1,000'
numeral(1000).format('$+0,0') === '$+1,000'

valueOf() support

Hello

I saw that you provide a value() method in order to retrieve the native value of the number.
Why not using the valueOf() method to do that, just like momentjs does? It'll make us able to use the object in comparisons such as obj > 1, and is better for semantic since it is a native method.

The implementation should be exactly like the value method:

    value : function () {
        return this._n;
    },

    valueOf : function () {
        return this._n;
    },

Fallback on setting languages

Currently, Numeral.js opts for throwing an exception when setting to a language that is not defined. For some environments, this may be desirable, for others it is rather unfortunate.

I propose to offer fallbacks (possibly on a different call that language to avoid changing the interface):

  • if de-AT is requested, but not found, de is tried instead; this allows one file for Germany and Austria (and Luxembourg), which are close enough in this case.
  • if hm is requested and not found, fall back to C which is some default that poduces sensible-enough formatting, probably exactly what plain JavaScript would do or perhaps en

Editing input value resets to 0

Loving Numeral.js! But I noticed this issue. The initial format of an entered value works just fine. But if you go back in to edit the value, it will reset to 0. The only time it doesn't reset to 0 is when you add digits to the front of the number.

0 -> input 1000
// 1,000

1,000 -> edit 1,010
// 0

Fix? Important when dealing with large values, typing the whole value back in each time is counter-intuitive and opens the opportunity for user typos / error. It doesn't like copy-paste either, but I suspect it's one and the same issue.

Thanks!

Expose languages collection

Hello,
numeral should expose the languages collection. This way the language definition is available.

In my case I'm removing the thousands delimiter and currency symbol from an input text and test if it's a number.

Example
var langData = numeral.languages()[numeral.language()];
var re = new RegExp('[' + langData.delimiters.thousands + langData.currency.symbol + ']', "g");
var rawValue = value.replace(re, '');
var isNumber = Number(rawValue);

Thanks

Overriding units

I'd like to know how you might suggest implementing Numeral in an application which needs to display both bits and bytes, as well as requiring decimal and binary prefixed versions for each.

I'm happy to work towards a pull request with such functionality, but given the way the API is put together at present, I can't see any clean way to specify multiple behaviours, or even just parameters.

Bytes in other languages

I believe you should add bytes suffix (MB,KB,...) to the language definition.
For example in french, KB = Ko (because "byte" = "octet").
If you do this I can pull request the french modifications.

Tagging 1.4.9 for Bower

Hey, can you for a git tag for 1.4.9? This helps when Bower users do

bower install numeral

Really appreciate your work! Thanks!

Create a tag for version 1.3.1

Hi,
I'm trying to create a webjar (http://www.webjars.org/) for numeral-js
But for now I can only download the lib via https://github.com/adamwdraper/Numeral-js/zipball/master and it lead me to 2 pbs :
a/ it is the trunk of the lib, and can change without notice
b/ the zip created has the following first level folder : adamwdraper-Numeral-js-15de409
with a tag 1.3.1 it would be adamwdraper-Numeral-js-1.3.1 (handled automatically by github)
which is a lot more friendly (no need to know the hash of the master)

Thx,

Parsing "1st" to 1

When you unformat "1st", it results in a trillion, because the 't' is recognised. While it should be 1.

Hide Zero

It would be nice if there is an option to not display zero values.

Website dropdown typo

In the dropdown to select a language it says Portogues (Portugual), it should say Portugal without the second u

Return a new numeral on math operations

Hi,

Would be great to return a new numeral instance on math operations like this:

var value = numeral(100),
    discount = numeral(0);

return value.subtract(value.multiply(discount).divide(numeral(100)));

It will return 0 instead of 90 since the value.multiply(discount) will change the value instance to 0 instead of returning a new instance with 0.

The idea is to mutate the numeral instance only using numeral.fn.set instead of mutating the called instance.

WDYT?

prefix and suffix

is there any chance to be able to add prefix or suffix in the format?

something like
$ 0[.]00 */pcs

can become to
$ 5.42 /pcs

btw, very useful lib :)

Validating a number

It would be great if numeraljs would allow to validate a given string to be a number (or not).

I was wondering if this would be possible by using a similar approach like unformat(), removing thousand separator, the abbreviations first, then taking the result of

string.replace(/[^0-9.-]+/g, '')

and determining if the length is different to the length of the source string (--> check if the string contained invalid characters).

What do you think?

Support for default currency formats in language files

The hypothetical scenario would be that you have an app that needs to be able to show a cost of something in various languages/currencies (which a ton of e-commerce sites do). It would be great if we could provide that to the developer rather than having them put a bunch of conditionals in their code so they can add the correct format.

It could then also be used in unformat for greater accuracy when working with the various language-specific currency formats — right now it's pretty inflexible.

Maybe similar to L, LL, LLL, and LLLL in Moment.js it would be something like:

$: $100k, € 500k, 500 tis. Kč, etc.
$$: $500,000, € 500.000, 500 000 Kč, etc.
$$$: $500,000.00, € 500.000,00, 500 000,00 Kč, etc.

Something like that — just quickly threw that together so it can obviously change. Feels like that's an area where Numeral-js could be really useful. Any thoughts? (I would be happy to write the code if there's interest.)

Inexact decimal subtraction

When a user subtracts a decimal from another decimal, the output can be inexact.

For example:

var firstNumber = numeral(123.1);
var secondNumber = numeral(123);

var result = firstNumber.subtract(secondNumber);

In this instance, result has the value of 0.09999999999999432 rather than 0.1.

Add support for locales

It shouldn't be that hard to implement. I took your numeral.js files and added some options.

numeral.delimiters = {
    thousands: ',',
    decimals: '.'
}

For french language, it should be something like that:

numeral.delimiters = {
    thousands: ' ',
    decimals: ','
}

Replace line 179 by

w = w.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1' + numeral.delimiters.thousands);

Replace line 188 by

d = numeral.delimiters.decimals + toFixed(n._n, precision.length).split('.')[1]; 

This is a quick fix to add different kind of delimiters. If you're interested to make that lib a bit more complete. I suggest you to take a look at babel.numbers

http://babel.edgewall.org/wiki/ApiDocs/babel.numbers

Having something similar to that in javascript would be simply awesome.

Language code should conform to some standard

At the moment, we have be-nl (where the country comes first) and en-gb (where the country comes second). This is confusing.

I propose adhering to some well-defined standard, cf. Wikipedia or what the HTTP Accept-Language header uses (BCP-47). The language comes first, the country is second and in uppercase. The languages from above would be nl-BE and en-GB.

1073741824 isn't converted to 1GB

numeral(1073741825).format('0b');
//"1GB"

numeral(1073741823).format('0b');
//"1024MB"

numeral(1073741824).format('0b');
//"1073741824"

3.7504E7 unformat error

3.7504E7 Should be unformat to 37,504,000 rather than 3.7504 or other values
Is there any way to fix it quickly? Thanks

Support for Indian and other similar number formats

Was just talking to a friend about this and in parts of India (or maybe everywhere in India) they format numbers like so: 1,00,00,000 (separator after hundreds until the last thousand) which right now, I believe, is impossible to re-create. There are probably other languages too that format their numbers like this or even more differently.

This is probably a substantial change to how Numeral-js does things. To solve, I assume Numeral-js would need to allow functions instead of objects for the "separator" property of a language which would then allow people to write their own custom formatters. The other possibility is allowing them to specify a custom format like so: '00,00,00,00,00,00,000.00' or something, but that seems kind of unwieldy since you have to make it arbitrarily big to make sure it always works.

Signed value

It would be nice if there could be option to always have signed value. In example:

numeral(-123.34).format('+0.0')  // -> -123.3
numeral(123.34).format('+0.0')   // -> +123.3

numeral(-123.34).format('+$0.0')  // -> -$123.3
numeral(123.34).format('+$0.0')   // -> +$123.3

amd support

I get this error when trying to do numeral.unformat('R1,000,000');

Uncaught TypeError: Object function (input) {
        if (numeral.isNumeral(input)) {
            input = input.value();
        } else if (!Number(input)) {
            input = 0;
        }

        return new Numeral(Number(input));
    } has no method 'unformat' 

I'm using requirejs

added italian version

please find here the italian language for numeral.js

// numeral.js language configuration
// language : italian Italy (it)
// author : Giacomo Trombi : http://cinquepunti.it
(function () {
    var language = {
        delimiters: {
            thousands: '.',
            decimal: ','
        },
        abbreviations: {
            thousand: 'mila',
            million: 'mil'
        },
        ordinal: function (number) {
            var b = number % 10;
            return '°';
        },
        currency: {
            symbol: '€'
        }
    };

    // Node
    if (typeof module !== 'undefined' && module.exports) {
        module.exports = language;
    }
    // Browser
    if (typeof window !== 'undefined' && this.numeral && this.numeral.language) {
        this.numeral.language('it', language);
    }
}());

Return a numeral on `numeral().unformat()`

Hi,

Would be great to be able to do something like this:

var value = numeral().unformat(value),
    discount = numeral().unformat(discount);

return value.subtract(discount);

Currently, the numeral.fn.unformat returns a Numeric instead of a instance of Numeral.

So I have to do that:

var value = numeral(numeral().unformat(value)),
    discount = numeral(numeral().unformat(discount));

return value.subtract(discount);

Makes sense?

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.