Skip to content

Commit

Permalink
fix(NumberPicker): float bug by chrome. Close #79
Browse files Browse the repository at this point in the history
  • Loading branch information
潕量 authored and tao1991123 committed Dec 18, 2018
1 parent 3128d8d commit 4ac7f41
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 5 deletions.
22 changes: 17 additions & 5 deletions src/number-picker/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,8 @@ class NumberPicker extends React.Component {
let result;
if (typeof val === 'number') {
result = (precisionFactor * val + precisionFactor * step) / precisionFactor;

result = this.hackChrome(result);
} else {
result = min === -Infinity ? step : min;
}
Expand All @@ -317,17 +319,27 @@ class NumberPicker extends React.Component {
if (typeof val === 'number') {
result = (precisionFactor * val - precisionFactor * step) / precisionFactor;

// in chrome browser: 0.3 - 0.2 = 0.09999999999, we should creact to 0.1
const precision = this.getPrecision();
if (precision > 0) {
result = Number(Number(result).toFixed(precision));
}
result = this.hackChrome(result);
} else {
result = min === -Infinity ? -step : min;
}
return result;
}

/**
* fix bug in chrome browser
* 0.28 + 0.01 = 0.29000000000000004
* 0.29 - 0.01 = 0.27999999999999997
* @param {Number} value value
*/
hackChrome(value) {
const precision = this.getPrecision();
if (precision > 0) {
return Number(Number(value).toFixed(precision));
}
return value;
}

step(type, e) {
if (e) {
e.preventDefault();
Expand Down
20 changes: 20 additions & 0 deletions test/number-picker/index-spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -318,4 +318,24 @@ describe('number-picker', () => {
done();
});
});
describe('chrome bug hack', () => {
it('0.28 + 0.01 should be 0.29 not 0.29000000000000004', (done) => {
let onChange = (value) => {
assert(value === 0.29);
done();
},
wrapper = mount(<NumberPicker defaultValue={0.28} onChange={onChange} step={0.01} precision={2}/>);

wrapper.find('button').at(0).simulate('click');
});
it('0.29 - 0.01 should be 0.28 not 0.27999999999999997', (done) => {
let onChange = (value) => {
assert(value === 0.28);
done();
},
wrapper = mount(<NumberPicker defaultValue={0.29} onChange={onChange} step={0.01} precision={2}/>);

wrapper.find('button').at(1).simulate('click');
});
});
});

0 comments on commit 4ac7f41

Please sign in to comment.