From 75af8e21bb88aefa8f848698ba4caebe909be340 Mon Sep 17 00:00:00 2001 From: Jorge M Date: Fri, 30 Aug 2024 14:33:13 +0200 Subject: [PATCH 1/2] Fomat shipping rate to two decimals --- src/Shipping/ShippingRate.php | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/Shipping/ShippingRate.php b/src/Shipping/ShippingRate.php index e2edef06c3..598d522879 100644 --- a/src/Shipping/ShippingRate.php +++ b/src/Shipping/ShippingRate.php @@ -37,7 +37,10 @@ class ShippingRate implements JsonSerializable { * @param float $rate The shipping cost in store currency. */ public function __construct( float $rate ) { - $this->rate = $rate; + // Google only accepts rates with two decimal places. + // We avoid using wc_format_decimal or number_format_i18n because these functions format numbers according to locale settings, which may include thousands separators and different decimal separators. + // At this stage, we want to ensure the number is formatted strictly as a float, with no thousands separators and a dot as the decimal separator. + $this->rate = (float) number_format( $rate, 2 ); } /** From 708910dbd59c1332f3134f4e5f94d43866422ea7 Mon Sep 17 00:00:00 2001 From: Jorge M Date: Fri, 30 Aug 2024 14:33:35 +0200 Subject: [PATCH 2/2] Add tests for shipping zone rate with more than 2 decimals --- tests/Unit/Shipping/ZoneMethodsParserTest.php | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/tests/Unit/Shipping/ZoneMethodsParserTest.php b/tests/Unit/Shipping/ZoneMethodsParserTest.php index 596ed7a3bc..372f6651f7 100644 --- a/tests/Unit/Shipping/ZoneMethodsParserTest.php +++ b/tests/Unit/Shipping/ZoneMethodsParserTest.php @@ -88,6 +88,27 @@ public function test_returns_flat_rate_methods_with_decimals_and_dot() { $this->assertEquals( 10.6, $shipping_rates[0]->get_rate() ); } + public function test_returns_flat_rate_methods_with_more_than_two_decimals() { + $flat_rate = $this->createMock( WC_Shipping_Flat_Rate::class ); + $flat_rate->id = ZoneMethodsParser::METHOD_FLAT_RATE; + $flat_rate->expects( $this->any() ) + ->method( 'get_option' ) + ->willReturnMap( + [ + [ 'cost', null, '10.6123' ], + ] + ); + + $zone = $this->createMock( WC_Shipping_Zone::class ); + $zone->expects( $this->any() ) + ->method( 'get_shipping_methods' ) + ->willReturn( [ $flat_rate ] ); + + $shipping_rates = $this->methods_parser->parse( $zone ); + $this->assertCount( 1, $shipping_rates ); + $this->assertEquals( 10.61, $shipping_rates[0]->get_rate() ); + } + public function test_returns_flat_rate_methods_including_shipping_classes() { // Return three sample shipping classes. $light_class = new \stdClass();