Git Product home page Git Product logo

javascript-number-formatter's Introduction

Javascript Number Formatter

Lightweight & Fast JavaScript Number Formatter

Build Status NPM Version devDependency Status MIT

Introduction

This standalone number formatter is intended to be short and fast. As they are the main factors for a high performance JavaScript app. Development release is around 150 lines including license info, blank lines and comments. And production release is less than 2,000 bytes.

format( "#,##0.####", 1234567.890 );  // output: "1,234,567.89"
format( "$ #,###.00", -1234567.890 ); // output: "$ -1,234,567.89"

// Added in v2.0.0
format( "$ #,###.00", -1234567.890, {enforceMaskSign: true});  // output: "$ 1,234,567.89"
format( "$ -#,###.00", -1234567.890, {enforceMaskSign: true}); // output: "$ -1,234,567.89"
format( "$ +#,###.00", -1234567.890, {enforceMaskSign: true}); // output: "$ -1,234,567.89"
format( "$ +#,###.00", 1234567.890, {enforceMaskSign: true});  // output: "$ +1,234,567.89"

† Initial development release of this code was written by KPL and hosted at Google Code.

Features

  • Short, fast, flexible yet standalone.
  • Accept standard number formatting like #,##0.00 or with negation -000.####.
  • Accept any country format like # ##0,00, #,###.##, #'###.## or any type of non-numbering symbol.
  • Accept any numbers of digit grouping. #,##,#0.000 or #,###0.## are all valid.
  • Accept any redundant/fool-proof formatting. ##,###,##.# or 0#,#00#.###0# are all OK.
  • Auto number rounding.
  • Simple interface, just supply mask & value like this: format( "0.0000", 3.141592).
  • Include a prefix & suffix with the mask.

Limitations

  • No scientific/engineering formatting.
  • Not for date or phone formation.
  • No color control.
  • No prefix or suffix is allowed except leading negation symbol. So $#,##0.00 or #,###.##USD will not yield expected outcome. Use '$'+format('#,##0.00', 123.45) or format('#,##0.00', 456.789) + 'USD'
  • The prefix or suffix can not include any numbers (0-9), dashes (-), or plus signs (+).

Format Symbols

Description Symbol Summary
Mask symbols #0123456789+- Mask symbols used for formatting the value.
Placeholders #123456789 Un-forced digit*; this optional digit will only show if it is required as a placeholder.
Zero 0 Forced digit; the digit will be shown whether or not the digit is relevant to the value.
Signs +- Indicates a positive or negative value; visible depending on the value sign and the enforceMaskSign setting.
Leftmost Any non-mask symbol† inside the mask will be set to represent a thousands separator.
Rightmost Any non-mask symbol† inside the mask‡ will be set to represent the decimal separator.
Prefix/Suffix Any non-mask symbol† outside the mask.

* Non-zero mask digits (1 through 9) behave the same as the #.
† Anything not a digit, and not a +, - or #.
‡ In the case where there is a trailing decimal or comma, it will be included in the mask, e.g. #. or 0,.

Note

When only one symbol is supplied, the library will always treat that symbol as a decimal. For example, format( '#,###', 1234567.890) will output 1234567,890.

To force a single symbol to be used as a separator, add a trailing symbol. In this example, a period is added to the end of the mask - format( '#,###.', 1234567.890) - resulting in it being used as a decimal and forcing the first symbol to be the separator and return this output: 1,234,567.

Installation

npm package

npm install --save number-format.js

Demos

A demo/sample page with few examples is provided (demo).

And a jsFiddle was created to aid in testing: https://jsfiddle.net/Mottie/t2etyodx/

Recent Changes

View the complete change log here.

v2.0.7 (2018-11-13)

  • Update typescript binding. See issue #20.
  • Fix improper placeholder behavior. Updated Readme with format symbols table. Closes issue #19.
  • Add more tests.
  • Meta:
    • Update dependencies.
    • Improve code readability.
    • Include version in min.js.

v2.0.6 (2018-11-06)

  • Trim trailing zeros in mask. Fixes issue #18.

v2.0.0 – 2.0.5 (2018-10-26)

  • Add ignoreSign option (modified to enforeceMaskSign!).
  • Switch to XO, AVA & rollup.
  • Meta: Update dot files & remove bower support.
  • Code cleanup & convert to ES2015.
    • Rename ignoreSign to enforceMaskSign (default false).
    • Reduce code complexity.
    • Export as node module.
    • Update TS with options.
    • Switch demo to use lib file & highlight valid results.
  • Switch from Grunt to rollup.
  • Switch from IIFE to UMD output.

javascript-number-formatter's People

Contributors

aaronhirsch avatar chuv avatar hyyan avatar junqdu avatar madmg avatar marcelboettcher avatar mottie 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

javascript-number-formatter's Issues

Mask with # as decimal is not working as expected

Hi @Mottie ,
First thank you for the library which is really useful.

Among all the examples you supplied in the README, there is this one:

format( "#,##0.####", 1234567.890 ); // output: "1,234,567.89"

The actual output is "1,234,567.8900"

I believe this is a bug since the # should fill the decimal only if necessary.

Different Handling for Negative "-" and Positive "+" Signs

Hello

Thanks for the great done job with this library, it is really the only stable and solid solution I could find for Javascript and the code is a state of art, easy to follow and well tested.

I would like to propose a different handling for negative and positive signs

The Current behavior

Sign Behavior
- The minus sign reverse the number sign
+ always ignored and omitted from the result

The New Behavior

Sign Behavior
- The minus sign creates a "-" in the result if the number is negative; otherwise ignored
+ The plus sign becomes a "+" in the result if the number is positive, or a "-" if the number is negative.

Examples compares between the new and the old behavior :

Number Mask Old Behavior New Behavior
-5000.123456789 -#,##0.###### 5,000.123457 -5,000.123457
5000.123456789 -#,##0.###### -5,000.123457 5,000.123457
-5000.123456789 #,##0.###### -5,000.123457 5,000.123457
+5000.123456789 +#,##0.###### 5,000.123457 +5,000.123457
+5000.123456789 #,##0.###### 5,000.123457 +5,000.123457
-5000.123456789 +#,##0.###### -5,000.123457 -5,000.123457

The new behavior makes more sense than the old one and it is less confusing. Of course such a change will not be a BC but I believe It’s worth it

I will send a PR for this feature and I hope it will be merged

Improve customization

Hi,
I'd like to be able to say 'format 0.5 as a percent' e.g.

format('###%', 0.5)

and it show as '50%', but I can't see a way to register customizations so ATM I have to do this outside of this library.

My feature request is more for the ability to add in custom masks, with perhaps a callback function rather than this specific example.

Just a suggestion while the re-write is going on :-)

John

Add rounding options

It's a piece of artwork with simplicity, I love this project.
In some cases, it's better to give the option to user of rounding options:
like:
t.is(format("#,##0.00", "123456.789"), "123,456.79");
t.is(format("#,##0.00", "123456.789", { rounding: 'floor'} ), "123,456.78");

jsFiddle doesn't work

Hi,
The example jsFiddle doesn't work straight away. There's a bug -

document.querySelector(".result").textContent = format(mask, value);

should be

document.querySelector(".result").textContent = format(mask, parseFloat(value, 10));

Thanks again for your hard work here!
John

Incorrect formatting when using #,##0 format

Hi, I'ma having a problem using the formatter: #,##0

In C#:
string.Format("{0:#,##0}", 0) ---> 0
string.Format("{0:#,##0}", 68) ---> 68

In the library:
format('#,##0', 0) ---> ,000
format('#,##0', 68) ---> 68,000

Can you please publish the latest to npm?

There's a confusing situation ATM where from npm you get 1.1.11 but the jsfiddle uses the github latest which says it's v 1.1.11 but I don't think it is as I think it's got the +/- sign change from about 6 months ago.

Can you publish the latest npm version please?

Thanks,
John

Incorrect result for large numbers

See example fiddle

  • Mask: # (for simplicity's sake)
  • Value: 12345678901234567890
  • Actual result: 12345678901234567000
  • Expected result: 12345678901234567890 (same as Value)

Remove trailing zeros for integer input OR improve documentation

In #18 trailing zeroes were supposedly fixed, however, I am unable to understand how to remove them completely when the input value is an integer. Here's my case:

expect(format("# ###,#", 19.9, {})).to.equal("19,9"); // pass
expect(format("# ###,#", 20, {})).to.equal("20"); // fail; actual output: "20,0"

I assume I'm not asking for something that your tool cannot do, but the documentation fails to explain the formatting strings. I do not understand what the various symbols (# vs 0) mean and how to use them to achieve what I need.

Support numeralJs-like abbreviations

Hi,
I noticed recently that NumeralJs includes abbreviations such as:

|    value | format | result
|  1230974 | '0.0a' |   1.2m
|     1460 |  '0 a' |    1 k
|  -104000 |   '0a' |  -104k

I was wondering if you had any plans on supporting such functionality? I mention it only because I know you are looking into rewriting this library and if it's not too much hassle this would be great to support. As an aside, NumeralJs also supports 'order' (1st, 2nd etc) too.

If/when this becomes critical to me I'll happily look into creating a PR.

Many thanks as always!
John

Improve TypeScript bindings

Current TypeScript typings mark the third parametre to the format function as required. However, as shown in the doc, it is clearly optional. It should be marked as optional in the TS typings as well.

In TS, in stead of writing:

format("# ###,#", 19.9, {});

I would like to be able to write:

format("# ###,#", 19.9);

Incorrect rounding number

We got issue on the rounding, example:
format("0.00", "7.165") got "7.17"
but
format("0.00", "8.165") got "8.16"

May I ask if any option can make them rounding consistent or this is a bug?

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.