Skip to content
This repository was archived by the owner on Feb 23, 2024. It is now read-only.

Commit 1f0102e

Browse files
committed
fix problem with price not rounding up right
1 parent be1da03 commit 1f0102e

File tree

2 files changed

+30
-7
lines changed

2 files changed

+30
-7
lines changed
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
export const ROUND_UP = 'ROUND_UP';
2+
export const ROUND_DOWN = 'ROUND_DOWN';

assets/js/blocks/price-filter/use-price-constraints.js

Lines changed: 28 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,31 @@
33
*/
44
import { usePrevious } from '@woocommerce/base-hooks';
55

6-
export const usePriceConstraint = ( price ) => {
7-
const currentConstraint = isNaN( price )
8-
? null
9-
: Math.floor( parseInt( price, 10 ) / 10 ) * 10;
6+
/**
7+
* Internal dependencies
8+
*/
9+
import { ROUND_UP, ROUND_DOWN } from './constants';
10+
11+
/**
12+
* Return the price constraint.
13+
*
14+
* @param {number} price Price in minor unit, e.g. cents.
15+
* @param {number} minorUnit Price minor unit (number of digits after the decimal separator).
16+
* @param {ROUND_UP|ROUND_DOWN} direction Rounding flag whether we round up or down.
17+
*/
18+
export const usePriceConstraint = ( price, minorUnit, direction ) => {
19+
const step = 10 * 10 ** minorUnit;
20+
let currentConstraint;
21+
if ( direction === ROUND_UP ) {
22+
currentConstraint = isNaN( price )
23+
? null
24+
: Math.ceil( parseFloat( price, 10 ) / step ) * step;
25+
} else if ( direction === ROUND_DOWN ) {
26+
currentConstraint = isNaN( price )
27+
? null
28+
: Math.floor( parseFloat( price, 10 ) / step ) * step;
29+
}
30+
1031
const previousConstraint = usePrevious( currentConstraint, ( val ) =>
1132
Number.isFinite( val )
1233
);
@@ -15,9 +36,9 @@ export const usePriceConstraint = ( price ) => {
1536
: previousConstraint;
1637
};
1738

18-
export default ( { minPrice, maxPrice } ) => {
39+
export default ( { minPrice, maxPrice, minorUnit } ) => {
1940
return {
20-
minConstraint: usePriceConstraint( minPrice ),
21-
maxConstraint: usePriceConstraint( maxPrice ),
41+
minConstraint: usePriceConstraint( minPrice, minorUnit, ROUND_DOWN ),
42+
maxConstraint: usePriceConstraint( maxPrice, minorUnit, ROUND_UP ),
2243
};
2344
};

0 commit comments

Comments
 (0)