Skip to content

Commit

Permalink
Render numbers with decimal instead of exponential notation in Input (
Browse files Browse the repository at this point in the history
#434)

Fixes #318
  • Loading branch information
kevva authored and sindresorhus committed Jul 25, 2018
1 parent 89363fc commit 8c612c5
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 1 deletion.
19 changes: 18 additions & 1 deletion app/renderer/components/Input.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import React from 'react';
import {classNames} from 'react-extras';
import propTypesRange from 'prop-types-range';
import './Input.scss';

const stripLeadingZeros = string => string.replace(/^0+(?=\d)/, '');
Expand All @@ -9,7 +10,18 @@ const fractionCount = string => {
return match ? match[1].length : 0;
};

const truncateFractions = (value, maximumFractionDigits) => Number.parseFloat(value).toLocaleString('fullwide', {
maximumFractionDigits,
useGrouping: false,
});

const isExponentialNotation = value => /(\d+\.?\d*)e\d*(\+|-)(\d+)/.test(value);

class Input extends React.Component {
static propTypes = {
fractionalDigits: propTypesRange(0, 20),
}

static getDerivedStateFromProps(props, state) {
return props.value === state.prevValue ? null : {
value: props.value,
Expand Down Expand Up @@ -127,9 +139,14 @@ class Input extends React.Component {
}

if (onlyNumeric) {
if (isExponentialNotation(value)) {
value = truncateFractions(value, 20); // 20 is the maximum, we truncate below instead
}

if (this._shouldTruncateFractions(value)) {
value = Number.parseFloat(value).toFixed(fractionalDigits);
value = truncateFractions(value, fractionalDigits);
}

value = this._truncateZeroOnlyFractions(value);
}

Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
"pouchdb-browser": "^7.0.0",
"pouchdb-find": "^7.0.0",
"prop-types": "^15.6.2",
"prop-types-range": "^0.0.0",
"qrcode.react": "^0.8.0",
"randoma": "^1.2.0",
"react": "^16.4.1",
Expand Down
6 changes: 6 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -7315,6 +7315,12 @@ promise@^7.1.1:
dependencies:
asap "~2.0.3"

prop-types-range@^0.0.0:
version "0.0.0"
resolved "https://registry.yarnpkg.com/prop-types-range/-/prop-types-range-0.0.0.tgz#1b2a615de0b1725fab1df596c1d2030291074215"
dependencies:
ow "^0.6.0"

prop-types@^15.5.10, prop-types@^15.5.8, prop-types@^15.6.0, prop-types@^15.6.1:
version "15.6.1"
resolved "https://registry.yarnpkg.com/prop-types/-/prop-types-15.6.1.tgz#36644453564255ddda391191fb3a125cbdf654ca"
Expand Down

0 comments on commit 8c612c5

Please sign in to comment.