Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle scientific notation numbers #444

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
node_modules/**/*
*.swp
.idea/
.DS_Store
*.log
.cache
Expand Down
7 changes: 7 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,10 @@ src/
test/
tmp/
flow-typed/
.idea/
.vscode/
.github/
example/
_config.yml
*.spec.tsx
typings/tsconfig.json
3 changes: 3 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"editor.formatOnSave": false
}
33 changes: 31 additions & 2 deletions dist/react-number-format.es.js
Original file line number Diff line number Diff line change
Expand Up @@ -257,9 +257,10 @@ function limitToScale(numStr, scale, fixedDecimalScale) {
function roundToPrecision(numStr, scale, fixedDecimalScale) {
//if number is empty don't do anything return empty string
if (['', '-'].indexOf(numStr) !== -1) return numStr;
var shoudHaveDecimalSeparator = numStr.indexOf('.') !== -1 && scale;
var normalizedNum = getRidOfScientificNotation(numStr);
var shoudHaveDecimalSeparator = normalizedNum.indexOf('.') !== -1 && scale;

var _splitDecimal = splitDecimal(numStr),
var _splitDecimal = splitDecimal(normalizedNum),
beforeDecimal = _splitDecimal.beforeDecimal,
afterDecimal = _splitDecimal.afterDecimal,
hasNagation = _splitDecimal.hasNagation;
Expand All @@ -277,6 +278,34 @@ function roundToPrecision(numStr, scale, fixedDecimalScale) {
var decimalSeparator = shoudHaveDecimalSeparator ? '.' : '';
return "".concat(negation).concat(intPart).concat(decimalSeparator).concat(decimalPart);
}
var SCIENTIFIC_NUMBER_REGEX = /\d+\.?\d*e[\+\-]?\d+/i;
function getRidOfScientificNotation(value) {
if (!SCIENTIFIC_NUMBER_REGEX.test(value)) {
return value;
} // This looks like a scientific notation. We will use parseFloat this time as this is not gonna be a limitation in this case


var number = parseFloat(value);

if (Math.abs(number) < 1.0) {
var e = parseInt(number.toString().split("e-")[1]);

if (e) {
number *= Math.pow(10, e - 1);
return "0." + new Array(e).join("0") + number.toString().substring(2);
}
} else {
var _e = parseInt(number.toString().split("+")[1]);

if (_e > 20) {
_e -= 20;
number /= Math.pow(10, _e);
return number + new Array(_e + 1).join("0");
}
}

return number.toString();
}
function omit(obj, keyMaps) {
var filteredObj = {};
Object.keys(obj).forEach(function (key) {
Expand Down
33 changes: 31 additions & 2 deletions dist/react-number-format.js
Original file line number Diff line number Diff line change
Expand Up @@ -263,9 +263,10 @@
function roundToPrecision(numStr, scale, fixedDecimalScale) {
//if number is empty don't do anything return empty string
if (['', '-'].indexOf(numStr) !== -1) return numStr;
var shoudHaveDecimalSeparator = numStr.indexOf('.') !== -1 && scale;
var normalizedNum = getRidOfScientificNotation(numStr);
var shoudHaveDecimalSeparator = normalizedNum.indexOf('.') !== -1 && scale;

var _splitDecimal = splitDecimal(numStr),
var _splitDecimal = splitDecimal(normalizedNum),
beforeDecimal = _splitDecimal.beforeDecimal,
afterDecimal = _splitDecimal.afterDecimal,
hasNagation = _splitDecimal.hasNagation;
Expand All @@ -283,6 +284,34 @@
var decimalSeparator = shoudHaveDecimalSeparator ? '.' : '';
return "".concat(negation).concat(intPart).concat(decimalSeparator).concat(decimalPart);
}
var SCIENTIFIC_NUMBER_REGEX = /\d+\.?\d*e[\+\-]?\d+/i;
function getRidOfScientificNotation(value) {
if (!SCIENTIFIC_NUMBER_REGEX.test(value)) {
return value;
} // This looks like a scientific notation. We will use parseFloat this time as this is not gonna be a limitation in this case


var number = parseFloat(value);

if (Math.abs(number) < 1.0) {
var e = parseInt(number.toString().split("e-")[1]);

if (e) {
number *= Math.pow(10, e - 1);
return "0." + new Array(e).join("0") + number.toString().substring(2);
}
} else {
var _e = parseInt(number.toString().split("+")[1]);

if (_e > 20) {
_e -= 20;
number /= Math.pow(10, _e);
return number + new Array(_e + 1).join("0");
}
}

return number.toString();
}
function omit(obj, keyMaps) {
var filteredObj = {};
Object.keys(obj).forEach(function (key) {
Expand Down
2 changes: 1 addition & 1 deletion dist/react-number-format.min.js

Large diffs are not rendered by default.

36 changes: 34 additions & 2 deletions lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ exports.splitDecimal = splitDecimal;
exports.fixLeadingZero = fixLeadingZero;
exports.limitToScale = limitToScale;
exports.roundToPrecision = roundToPrecision;
exports.getRidOfScientificNotation = getRidOfScientificNotation;
exports.omit = omit;
exports.setCaretPosition = setCaretPosition;
exports.findChangedIndex = findChangedIndex;
Expand Down Expand Up @@ -112,9 +113,10 @@ function limitToScale(numStr, scale, fixedDecimalScale) {
function roundToPrecision(numStr, scale, fixedDecimalScale) {
//if number is empty don't do anything return empty string
if (['', '-'].indexOf(numStr) !== -1) return numStr;
var shoudHaveDecimalSeparator = numStr.indexOf('.') !== -1 && scale;
var normalizedNum = getRidOfScientificNotation(numStr);
var shoudHaveDecimalSeparator = normalizedNum.indexOf('.') !== -1 && scale;

var _splitDecimal = splitDecimal(numStr),
var _splitDecimal = splitDecimal(normalizedNum),
beforeDecimal = _splitDecimal.beforeDecimal,
afterDecimal = _splitDecimal.afterDecimal,
hasNagation = _splitDecimal.hasNagation;
Expand All @@ -133,6 +135,36 @@ function roundToPrecision(numStr, scale, fixedDecimalScale) {
return "".concat(negation).concat(intPart).concat(decimalSeparator).concat(decimalPart);
}

var SCIENTIFIC_NUMBER_REGEX = /\d+\.?\d*e[\+\-]?\d+/i;

function getRidOfScientificNotation(value) {
if (!SCIENTIFIC_NUMBER_REGEX.test(value)) {
return value;
} // This looks like a scientific notation. We will use parseFloat this time as this is not gonna be a limitation in this case


var number = parseFloat(value);

if (Math.abs(number) < 1.0) {
var e = parseInt(number.toString().split("e-")[1]);

if (e) {
number *= Math.pow(10, e - 1);
return "0." + new Array(e).join("0") + number.toString().substring(2);
}
} else {
var _e = parseInt(number.toString().split("+")[1]);

if (_e > 20) {
_e -= 20;
number /= Math.pow(10, _e);
return number + new Array(_e + 1).join("0");
}
}

return number.toString();
}

function omit(obj, keyMaps) {
var filteredObj = {};
Object.keys(obj).forEach(function (key) {
Expand Down
1 change: 0 additions & 1 deletion src/number_format.js
Original file line number Diff line number Diff line change
Expand Up @@ -540,7 +540,6 @@ class NumberFormat extends React.Component {

// if value is not defined return empty string
if (isNonNumericFalsy && !allowEmptyFormatting) return '';

if (typeof value === 'number') {
value = value.toString();
isNumericString = true;
Expand Down
31 changes: 29 additions & 2 deletions src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,9 @@ export function roundToPrecision(numStr: string, scale: number, fixedDecimalScal
//if number is empty don't do anything return empty string
if (['', '-'].indexOf(numStr) !== -1) return numStr;

const shoudHaveDecimalSeparator = numStr.indexOf('.') !== -1 && scale;
const {beforeDecimal, afterDecimal, hasNagation} = splitDecimal(numStr);
const normalizedNum = getRidOfScientificNotation(numStr);
const shoudHaveDecimalSeparator = normalizedNum.indexOf('.') !== -1 && scale;
const {beforeDecimal, afterDecimal, hasNagation} = splitDecimal(normalizedNum);
const roundedDecimalParts = parseFloat(`0.${afterDecimal || '0'}`).toFixed(scale).split('.');
const intPart = beforeDecimal.split('').reverse().reduce((roundedStr, current, idx) => {
if (roundedStr.length > idx) {
Expand All @@ -103,6 +104,32 @@ export function roundToPrecision(numStr: string, scale: number, fixedDecimalScal
return `${negation}${intPart}${decimalSeparator}${decimalPart}`;
}

const SCIENTIFIC_NUMBER_REGEX = /\d+\.?\d*e[+-]?\d+/i;

export function getRidOfScientificNotation(value: string) {
if (!SCIENTIFIC_NUMBER_REGEX.test(value)) {
return value;
}

// This looks like a scientific notation. We will use parseFloat this time as this is not gonna be a limitation in this case
let number = parseFloat(value);
if (Math.abs(number) < 1.0) {
const e = parseInt(number.toString().split("e-")[1], 10);
if (e) {
number *= Math.pow(10, e - 1);
return "0." + new Array(e).join("0") + number.toString().substring(2);
}
} else {
let e = parseInt(number.toString().split("+")[1], 10);
if (e > 20) {
e -= 20;
number /= Math.pow(10, e);
return number + new Array(e + 1).join("0");
}
}
return number.toString();
}


export function omit(obj: Object, keyMaps: Object) {
const filteredObj = {};
Expand Down
15 changes: 15 additions & 0 deletions test/library/format_as_text.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,21 @@ describe('NumberFormat as text', () => {
expect(wrapper.find('span').text()).toEqual('4111 1111 1111 1111');
});

it('should format small number in a scientific notation properly', () => {
const wrapper = shallow(<NumberFormat displayType="text" value={4.1e-7} thousandSeparator={' '} decimalScale={10} />);
expect(wrapper.find("span").text()).toEqual("0.00000041");
});

it('should format really small number properly', () => {
const wrapper = shallow(<NumberFormat displayType="text" value={0.00000041} thousandSeparator={' '} decimalScale={10} />);
expect(wrapper.find("span").text()).toEqual("0.00000041");
});

it('should format big number in a scientific notation properly', () => {
const wrapper = shallow(<NumberFormat displayType="text" value={4.1E10} thousandSeparator={' '} />);
expect(wrapper.find("span").text()).toEqual("41 000 000 000");
});

it('should format as given format when input is string', () => {
const wrapper = shallow(<NumberFormat value="4111111111111111" displayType={'text'} format="#### #### #### ####" />);
expect(wrapper.find('span').text()).toEqual('4111 1111 1111 1111');
Expand Down