Number formatted js library

Numeral.js, Is a Formatting Numbers and Deal with numbers Of js library .

Tip: at present Star Yes 9.2k,5 It was not updated years ago . Its file Not very clearly written , For example, it provides multiple languages , But how to switch to Chinese , How to use it without saying , For some problems (abbreviations Report errors ) The author only from the source code 、 Update logs and Issues In search of answers .

Use it

node Pass through npm Can be installed :

PS E:\react-project> npm i numeral

Tip: It can also be directly accessed in the browser src The way to use .

Create examples

adopt numeral() Create an instance :

var myNumeral = numeral(1000);
var value = myNumeral.value();
// value 1000
console.log('value', value)

Feel good chicken ribs , But it can Unformatted . For example, will 1,000 Processing into 1000

var myNumeral2 = numeral('1,000');
var value2 = myNumeral2.value();
// value2 1000
console.log('value2', value2)

format

This part is what we are most concerned about . For example, the author needs :

  • Automatically convert the number of bytes in the background to according to the size of the value KBMBGB And so on
  • The number is too long , Limited display area , For example, will 123456789 To 123.5m or 123.5 One million

format()

adopt format() Can be 1000 Format as 1,000, take 123456789 Format as 123,456,789. See the example :

var number = numeral(1000).format('0,0');
// number: 1,000
console.log('number: ', number);
var number2 = numeral(123456789).format('0,0');
// number2: 123,456,789
console.log('number2: ', number2);
// rounding
var number3 = numeral(1.93).format('0,0');
// number3: 2
console.log('number3: ', number3);
// rounding
var number4 = numeral(1.23).format('0,0');
// number4: 1
console.log('number4: ', number4);

Tip: We used it 0,0 This format , For other formats, please see numeral.js:

// node_modules\numeral\tests\numeral.js
describe('Format', function() {
it('should format to a number', function() {
var tests = [
[0, null, '0'],
[0, '0.00', '0.00'],
[null, null, '0'],
[NaN, '0.0', '0.0'],
[1.23,'0,0','1'],
[10000,'0,0.0000','10,000.0000'],
[10000.23,'0,0','10,000'],
[-10000,'0,0.0','-10,000.0'],
[10000.1234,'0.000','10000.123'],
[10000,'0[.]00','10000'],
[10000.1,'0[.]00','10000.10'],
[10000.123,'0[.]00','10000.12'],
[10000.456,'0[.]00','10000.46'],
[10000.001,'0[.]00','10000'],
[10000.45,'0[.]00[0]','10000.45'],
[10000.456,'0[.]00[0]','10000.456'],
[10000,'(0,0.0000)','10,000.0000'],
[-10000,'(0,0.0000)','(10,000.0000)'],
[-12300,'+0,0.0000','-12,300.0000'],
[1230,'+0,0','+1,230'],
[1230,'-0,0','1,230'],
[-1230,'-0,0','-1,230'],
[-1230.4,'0,0.0+','1,230.4-'],
[-1230.4,'0,0.0-','1,230.4-'],
[1230.4,'0,0.0-','1,230.4'],
[100.78, '0', '101'],
[100.28, '0', '100'],
[1.932,'0.0','1.9'],
[1.9687,'0','2'],
[1.9687,'0.0','2.0'],
[-0.23,'.00','-.23'],
[-0.23,'(.00)','(.23)'],
[0.23,'0.00000','0.23000'],
[0.67,'0.0[0000]','0.67'],
[3162.63,'0.0[00000000000000]','3162.63'],
[1.99,'0.[0]','2'],
[1.0501,'0.00[0]','1.05'],
[1.005,'0.00','1.01'],
// leading zero
[0, '00.0', '00.0'],
[0.23, '000.[00]', '000.23'],
[4, '000', '004'],
[10, '00000', '00010'],
[1000, '000,0', '1,000'],
[1000, '00000,0', '01,000'],
[1000, '0000000,0', '0,001,000'],
// abbreviations
[2000000000,'0.0a','2.0b'],
[1230974,'0.0a','1.2m'],
[1460,'0a','1k'],
[-104000,'0 a','-104 k'],
[999950,'0.0a','1.0m'],
[999999999,'0a','1b'],
// forced abbreviations
[-5444333222111, '0,0 ak', '-5,444,333,222 k'],
[5444333222111, '0,0 am', '5,444,333 m'],
[-5444333222111, '0,0 ab', '-5,444 b'],
[-5444333222111, '0,0 at', '-5 t'],
[123456, '0.0[0] ak', '123.46 k'],
[150,'0.0 ak','0.2 k']
],
i,
n,
output; for (i = 0; i < tests.length; i++) {
n = numeral(tests[i][0]);
output = n.format(tests[i][1]); expect(output).to.equal(tests[i][2]); expect(typeof output).to.equal('string');
}
});
});

Byte conversion

For example, will 1024 To 1KB, take 1024*1024 To 1MB. We will look at an example :

PS D:\spug-study> node
Welcome to Node.js v16.14.2.
Type ".help" for more information.
> let numeral = require('numeral')
undefined
> numeral(1024).format('0b')
'1KB'
> numeral(1024*1024).format('0b')
'1MB'
> numeral(1024*1024*1024).format('0b')
'1GB'
> numeral(1024*1024*1024*1024).format('0b')
'1TB'
> numeral(1024*1024*1024*1024*32).format('0b')
'35TB'
>

Tip: The author is directly in node Operation in environment . For more formatting syntax, see bytes.js file .

// node_modules\numeral\tests\formats\bytes.js
it('should format to bytes', function() {
var decimal = 1000;
var binary = 1024;
var tests = [
[0,'0b','0B'],
[null,'0 b','0 B'],
[100,'0b','100B'],
[binary * 2,'0 ib','2 KiB'],
[Math.pow(binary, 2) * 5,'0ib','5MiB'],
[Math.pow(binary, 3) * 7.343,'0.[0] ib','7.3 GiB'],
[Math.pow(binary, 4) * 3.1536544,'0.000ib','3.154TiB'],
[Math.pow(binary, 5) * 2.953454534534,'0ib','3PiB'],
[decimal * 2,'0 b','2 KB'],
[Math.pow(decimal, 2) * 5,'0b','5MB'],
[Math.pow(decimal, 3) * 7.343,'0.[0] b','7.3 GB'],
[Math.pow(decimal, 4) * 3.1536544,'0.000b','3.154TB'],
[Math.pow(decimal, 5) * 2.953454534534,'0b','3PB']
],
i; for (i = 0; i < tests.length; i++) {
expect(numeral(tests[i][0]).format(tests[i][1])).to.equal(tests[i][2]);
}
});
Byte to number

For example, you can 1KB Turn to numbers , But the result is just 1000, If you want to 1024, Need to use 1 KiB. See the example :

> numeral('1KB').value()
1000
> numeral('1 KiB').value()
1024
> numeral('1MB').value()
1000000

Tip: of Byte anti parsing For more information on bytes.js.

// node_modules\numeral\tests\formats\bytes.js
it('should unformat to number', function() {
var decimal = 1000;
var binary = 1024;
var tests = [
['0B', 0],
['0 B', 0],
['100B', 100],
['2 KiB', binary * 2],
['5MiB', Math.pow(binary, 2) * 5],
['7.3 GiB', Math.pow(binary, 3) * 7.3],
['3.154TiB', Math.pow(binary, 4) * 3.154],
['3PiB', Math.pow(binary, 5) * 3],
['2 KB', decimal * 2],
['5MB', Math.pow(decimal, 2) * 5],
['7.3 GB', Math.pow(decimal, 3) * 7.3],
['3.154TB', Math.pow(decimal, 4) * 3.154],
['3PB', Math.pow(decimal, 5) * 3]
],
i; for (i = 0; i < tests.length; i++) {
expect(numeral(tests[i][0]).value()).to.equal(tests[i][1]);
}
});

Time conversion

The digital ( second ) Change to time form . See the example :

> numeral(1).format('00:00:00')
'0:00:01'
> numeral(60).format('00:00:00')
'0:01:00'
> numeral(60*60).format('00:00:00')
'1:00:00'

Percentage conversion

See the example :

> numeral(0.974878234).format('0.000%')
'97.488%'
> numeral(0).format('0%')
'0%'
> numeral(1).format('0%')
'100%'

Tip: For more information, please see node_modules\numeral\tests\formats\percentage.js.

Currency conversion

See the example :

> numeral(1000.234).format('$0,0.00')
'$1,000.23'

Tip: For more usage, see currency.js.

// node_modules\numeral\tests\formats\currency.js
describe('Currency', function() {
after(function() {
numeral.reset();
}); it('should format to currency', function() {
var tests = [
[0,'$0.00','$0.00'],
[null,'$0.00','$0.00'],
[0.99,'$0,0.00','$0.99'],
[1000.234,'$0,0.00','$1,000.23'],
[1001,'$ 0,0.[00]','$ 1,001'],
[1000.234,'0,0.00 $','1,000.23 $'],
[-1000.234,'0,0.00 $','-1,000.23 $'],
[-1000.234,'($0,0)','($1,000)'],
[-1000.234,'(0,0$)','(1,000$)'],
[-1000.234,'(0,0 $)','(1,000 $)'],
[-1000.234,'$0.00','-$1000.23'],
[-1000.234,'$ 0.00','-$ 1000.23'],
[1230974,'($0.00 a)','$1.23 m'],
[-1000.234,'$ (0,0)','$ (1,000)'],
[-1000.234,'$(0,0)','$(1,000)'],
[-1000.234,'$ (0,0.00)','$ (1,000.23)'],
[-1000.234,'$(0,0.00)','$(1,000.23)'],
[-1000.238,'$(0,0.00)','$(1,000.24)'],
[-1000.234,'$-0,0','$-1,000'],
[-1000.234,'$ -0,0','$ -1,000'],
[1000.234,'$ (0,0)','$ 1,000'],
[1000.234,'$(0,0)','$1,000'],
[1000.234,'$ (0,0.00)','$ 1,000.23'],
[1000.234,'$(0,0.00)','$1,000.23'],
[1000.238,'$(0,0.00)','$1,000.24'],
[1000.234,'$-0,0','$1,000'],
[1000.234,'$ -0,0','$ 1,000']
],
i; for (i = 0; i < tests.length; i++) {
expect(numeral(tests[i][0]).format(tests[i][1])).to.equal(tests[i][2]);
}
}); it('should unformat to currency', function() {
var tests = [
['$0.00', 0],
['$0.99', 0.99],
['$1,000.23', 1000.23],
['1,000.23 $', 1000.23],
['($1,000)', -1000],
['-1,000$', -1000],
['$1.23 m', 1230000],
],
i; for (i = 0; i < tests.length; i++) {
expect(numeral(tests[i][0]).value()).to.equal(tests[i][1]);
}
});
});

Exponential transformation

See the example :

> numeral(77777777.1234).format('0.0e+0')
'7.8e+7'

Tip: For more usage, see exponential.js.

// node_modules\numeral\tests\formats\exponential.js
it('should format to exponential notation', function() {
var tests = [
[0,'0e+0','0e+0'],
[null,'0e+0','0e+0'],
[1,'0e+0','1e+0'],
[77.1234,'0.0e+0','7.7e+1'],
[0.000000771234,'0.0e-0','7.7e-7'],
[-0.000000771234,'0.00e-0','-7.71e-7'],
[77.1234,'0.000e+0','7.712e+1'],
[-1000830298,'0.0[000]e+0','-1.0008e+9']
],
i; for (i = 0; i < tests.length; i++) {
expect(numeral(tests[i][0]).format(tests[i][1])).to.equal(tests[i][2]);
}
});

Bit rate conversion

Bit rate , It refers to the bits transmitted per unit time (bit) Count , Unit is bps(bit per second).

> numeral(.0056).format('0 BPS')
'56 BPS'

Tip: For more usage, see bps.js

// node_modules\numeral\tests\formats\bps.js
it('should format to bps', function() {
var tests = [
[0,'0 BPS','0 BPS'],
[0.0001, '0 BPS', '1 BPS'],
[.0056, '0 BPS', '56 BPS'],
[.25, '0BPS', '2500BPS'],
[.000001, '0.00 BPS', '0.01 BPS']
],
i; for (i = 0; i < tests.length; i++) {
expect(numeral(tests[i][0]).format(tests[i][1])).to.equal(tests[i][2]);
}
});

arithmetic

numeral Provide Add, subtract, multiply and divide Four methods of operation , for example 1000 Add 10 be equal to 1010. See the example :

> numeral(1000).add(10).value()
1010

Tip: For more information, please see numeral.js.

// node_modules\numeral\tests\numeral.js
describe('Manipulate', function() {
// Add
describe('Add', function() {
it('should add', function() {
var tests = [
[1000,10,1010],
[0.5,3,3.5],
[-100,200,100],
[0.1,0.2,0.3],
[0.28,0.01,0.29],
[0.289999,0.000001,0.29],
[0.29,0.01,0.3]
],
num; for (var i = 0; i < tests.length; i++) {
num = numeral(tests[i][0]); num.add(tests[i][1]); expect(num.value()).to.equal(tests[i][2]);
}
});
}); // Subtraction
describe('Subtract', function() {
it('should subtract', function() {
var tests = [
[1000,10,990],
[0.5,3,-2.5],
[-100,200,-300],
[0.3,0.1,0.2],
[0.28,0.01,0.27],
[0.29,0.01,0.28]
],
num; for (var i = 0; i < tests.length; i++) {
num = numeral(tests[i][0]); num.subtract(tests[i][1]); expect(num.value()).to.equal(tests[i][2]);
}
});
}); // Multiplication
describe('Multiply', function() {
it('should multiply', function() {
var tests = [
[1000,10,10000],
[0.5,3,1.5],
[-100,200,-20000],
[0.1,0.2,0.02],
[0.28,0.01,0.0028],
[0.29,0.01,0.0029],
[0.00000231,10000000,23.1]
],
num; for (var i = 0; i < tests.length; i++) {
num = numeral(tests[i][0]); num.multiply(tests[i][1]); expect(num.value()).to.equal(tests[i][2]);
}
});
}); // division
describe('Divide', function() {
it('should divide', function() {
var tests = [
[1000,10,100],
[0.5,3,0.16666666666666666],
[-100,200,-0.5],
[5.3,0.1,53],
[0.28,0.01,28],
[0.29,0.01,29]
],
num; for (var i = 0; i < tests.length; i++) {
num = numeral(tests[i][0]); num.divide(tests[i][1]); expect(num.value()).to.equal(tests[i][2]);
}
});
}); // Difference value . for example 1000 and 10 Difference between 990.
describe('Difference', function() {
it('should find a difference', function() {
var tests = [
[1000,10,990],
[0.5,3,2.5],
[-100,200,300],
[0.3,0.2,0.1],
[0.28,0.01,0.27],
[0.29,0.01,0.28]
],
num; for (var i = 0; i < tests.length; i++) {
num = numeral(tests[i][0]); expect(num.difference(tests[i][1])).to.equal(tests[i][2]);
}
});
}); // rounding .
describe('Rounding', function() {
it('should format with rounding', function() {
var tests = [
// value, format string, expected w/ floor, expected w/ ceil
[2280002, '0.00a', '2.28m', '2.29m'],
[10000.23,'0,0','10,000', '10,001'],
[1000.234,'0,0.00','1,000.23', '1,000.24'],
[0.97487823,'0.000','0.974','0.975'],
[-0.433,'0.0','-0.5', '-0.4']
],
i; for (i = 0; i < tests.length; i++) {
// floor
expect(numeral(tests[i][0]).format(tests[i][1], Math.floor)).to.equal(tests[i][2]); // ceil
expect(numeral(tests[i][0]).format(tests[i][1], Math.ceil)).to.equal(tests[i][3]);
}
});
});
});

Multilingual

demand : When the numbers are very long , Due to the consideration of typesetting , You need to display the numbers shorter , To Index Just about , But still not friendly to many people , If you can change to 123.5 One million This form is perfect .

numeral Provides abbreviation , For example, you can 1230974 To 1.2m(m, finger One million ):

// node_modules\numeral\tests\numeral.js
...
// abbreviations
[2000000000,'0.0a','2.0b'],
[1230974,'0.0a','1.2m'],
[1460,'0a','1k'],
[-104000,'0 a','-104 k'],
[999950,'0.0a','1.0m'],
[999999999,'0a','1b'],

See the example :

const numeral = require('numeral');
var number5 = numeral(123456789).format('0.0a')
// 123.5m
console.log('number5: ', number5);

123.5m How much is the , Can it be translated into Chinese ? The author is in chs.js Find the following code in :

// node_modules\numeral\locales\chs.js

numeral.register('locale', 'chs', {
delimiters: {
thousands: ',',
decimal: '.'
},
abbreviations: {
thousand: ' thousand ',
million: ' One million ',
billion: ' One billion ',
trillion: ' mega '
},
ordinal: function (number) {
return '.';
},
currency: {
symbol: '¥'
}
});

By introducing chs And switch to Chinese , Will succeed 123456789 To 123.5 One million . See the example :

const numeral = require('numeral');
// Load Chinese
+ require('numeral/locales/chs')
// Switch to Chinese
+ numeral.locale('chs')
const number5 = numeral(123456789).format('0.0a')
// number5: 123.5 One million
console.log('number5: ', number5);

Tip: For single page projects , If English is required in other components , For example, don't 123.5 One million , But to 123.5m, Switch languages directly (numeral.locale('en')) that will do . Just like this. :

...
const number5 = numeral(123456789).format('0.0a')
// number5: 123.5 One million
console.log('number5: ', number5); + numeral.locale('en')
const number6 = numeral(123456789).format('0.0a') // number6: 123.5m
console.log('number6: ', number6);

The author's example

import React from 'react';
const numeral = require('numeral');
require('numeral/locales/chs')
numeral.locale('chs') function Test() {
const number = numeral(1000).format('0,0');
// number: 1,000
console.log('number: ', number);
const number2 = numeral(123456789).format('0,0');
// number2: 123,456,789
console.log('number2: ', number2);
// rounding
const number3 = numeral(1.93).format('0,0');
// number3: 2
console.log('number3: ', number3);
// rounding
const number4 = numeral(1.23).format('0,0');
// number4: 1
console.log('number4: ', number4); const number5 = numeral(123456789).format('0.0a')
// number5: 123.5 One million
console.log('number5: ', number5); numeral.locale('en')
const number6 = numeral(123456789).format('0.0a') // number6: 123.5m
console.log('number6: ', number6);
return (
<div>
react project
</div>
)
} export default Test

Number formatted js More articles about the library

  1. Numeral.js It is used for formatting and four arithmetic operations of numbers js library

    1.Numeral.js It is used for formatting and four arithmetic operations of numbers js library . 2. Support for multiple languages , Including Chinese 17 Languages . Reference... In the browser js file : <script src="numeral. ...

  2. js Financial number formatting

    js Financial number formatting finance money number format Number formatting regex `123456789`.replace(/\B(?=(\d{3})+(?!\d))/g, ',') ...

  3. js Number formatting - Round down the condensed version

    Search the Internet , The number format is too complex , I thought of a simple way , Make complaints about Tucao . Simplified description : '123333' => 12.3 ten thousand parseInt('123333') String to integer parseInt('12333 ...

  4. Vue-admin Work arrangement ( nineteen ): Talking about the third party from the digital gradient component JS library Count-to Use

    1. Component packaging foundation npm install [email protected] 2. Used in components id value 3. Get in component dom How to package a component , When used in a component, you need to pass in HTML Elements ID It's worth it JS How to deal with the library , How to get ...

  5. js Number formatting ( Truncation formatting or rounding formatting )

    /*** * Number formatting ( It is suitable for financial products to be displayed after decimals are cut off ) * @param num * @param pattern ( A standard format :#,###.## or #.## or #,###00.00) * @para ...

  6. Main stream JS Library at a glance

    Main stream JS Library at a glance label : prototypedojomootoolsprototypejsjqueryjavascript 2009-10-14 22:52 19936 Human reading   Comment on (2)  Collection   report   ...

  7. 12 A top-level visualization worthy of attention JS library Involving charts 、 Animation 、 Time processing , Form operation

    This article is a translation , The original is https://da-14.com/blog/top-11... I added Baidu's on the basis of the original Echats Chart Library , This is not inferior to other chart libraries . in addition Handsontable So is the spreadsheet library ...

  8. Recently js A problem of discrimination encountered in the library

    Recently, I'm writing my own js library , Writing to array package , There is a sort defined in it , A way to sort only pure digital data , But I found a very strange problem during the test , That's when you pass in an object , It didn't return erroemsg Instead, it returns the object , On ...

  9. Use .toLocaleString() Easily format price numbers in multiple languages

    Format numbers in code , Obviously, it is not as simple as adding a comma to every three digits . For example, India's treatment of the numeral quantile symbol , It can be called a wonderful flower in the industry : In India, the number is read in “ lakshmi ”( One hundred thousand ) and “ crore ”( Ten million ), Numerical notation uses asymmetric digit separation , That is, the first to the left of the decimal point ...

  10. impress.js A way to create an online slide js library

    It's really strange , I can blog about front end technology . There's no way , Recent internship , It's mostly the front end . So today I'll use this to practice my hand . Impress.js It's a great way to create online demos Javascript library . It's based on CSS3 turn ...

Random recommendation

  1. boost Event handling

    Although the name of the library may seem misleading at first glance , But it's not like that . Boost.Signals The implemented pattern is named ' Signal to slot ' (signal to slot). It is based on the following concepts : When the corresponding signal is sent . relevant ...

  2. Signal due to problem ORA-27154 Unable to start database

    The test library runs startup When the system prompts (11.2.0.1): Inquire about ORA-27154 Error of : Error: ORA-27154 Text: post/wait create failed -------- ...

  3. C# Summary of generic Basics

    1.0   What is generics Generics are C#2.0 and CLR( Common language runtime ) A new feature of the upgrade , The generics are .NET The framework introduces a called type parameters( Type parameter ) The concept of ,type parameters send ...

  4. 【 Development technology 】 Encrypt the contents of the file -java

    http://hi.baidu.com/java0804ms/item/111ea834fbd4d2f596f88d5a Realization effect : Encrypt the contents of the file , Make it open directly and become garbled , Not in clear text Implementation steps :1 ...

  5. Tanzhou classroom 25 class :Ph201805201 django project Lesson 7 User model design ( Class notes

    stay user In the application of models.py: Import dango Built in user model from django.contrib.auth.models import AbstractUser,UserMan ...

  6. tgp The assistant has no response when opening the anti war game

    tgp The assistant has no response when opening the anti war game ( Always show that the game is running ) There is no game login interface Some of the solutions ( Not necessarily effective ): Check the driver of the graphics card Check the game file for damage Check whether the protection software program is turned on

  7. Java Permission modifiers in private、protected、public

    java Modifier classification in : Permission modifier : private, default, protected, public Status modifier : static, final Abstract modifier : abstract Permission modifier I ...

  8. java web Garbled code ends

    To configure tomcat open tomcat Under the installation path conf/server.xml file , take port by 8080 Of connector Make the following changes : <Connector port=&q ...

  9. 《Python The road of automatic operation and maintenance 》 System basic information module ( One )

    System performance collection module Psutil Catalog : System performance information module psutil System performance information module psutil psutil Can easily achieve access to the system running process and system utilization, including (CPU, Memory , disk And the Internet ) etc. . It's mainly used for ...

  10. [AHOI2013] Homework

    [AHOI2013] Homework The main idea of the topic : Given a length of \(n(n\le10^5)\) Sequence of numbers \(A(1\le A_i\le n)\).\(m(m\le10^6)\) Time to ask , The interval of each inquiry \([l,r]\) Inside ...