Need help with grid snapping

I have a grid snapping logic which works on grid with size 4 columns 2 rows even if I rotate the grid and in 3 columns 2 rows too but in the second grid when rotated the modelSelected(object that is snapped) snaps it self to the points where grid lines intersect and not to the center of the cells. Below is the logic I’m using. I just don’t understand how it works on 4x2, 2x4 and 3x2 too but not with 2x3.

if (modelSelected.position) {
    const intersectedPosition = intersectedObject.position;
    // Calculate grid cell dimensions
    const gridCellWidth = gridSize.width / seletedGridDimension[0];
    const gridCellHeight = gridSize.height / seletedGridDimension[1];
    
    // Calculate the offset from the origin of the grid
    const offsetX = (gridSize.width % gridCellWidth) / 2;
    const offsetY = (gridSize.height % gridCellHeight) / 2;
    
    // Calculate the snapped position for X
    const snappedX = Math.floor((intersect.point.x - intersectedPosition.x + offsetX) / gridCellWidth) * gridCellWidth - offsetX + (gridCellWidth / 2);
    let snappedY;
    // Special case for grids with 1 row (no need to snap on Y axis)
    if (seletedGridDimension[1] === 1) {
    snappedY = 0; // No snapping on Y if it's a single row grid
    } else {
    // Calculate the snapped position for Y
    snappedY = Math.floor((intersect.point.y - intersectedPosition.y + offsetY) / gridCellHeight) * gridCellHeight - offsetY + (gridCellHeight / 2);
    }
    
    // Set the new position of the model
    modelSelected.position.set(
    intersectedPosition.x + snappedX,
    intersectedPosition.y + snappedY,
    intersect.point.z
    );
    
    Render();

If I were you, I’d debug the code for 2x3 and will inspect the values of all local variables. In this way it will be easier to find which calculation produces a wrong result. Usually this gives enough clues to identify the problem.

You might even find out that some of the working cases are also wrong, but they reach the correct result just by accident.

I am not sure if this Showcase topic might be of any help but it at least has grid snapping and there is a link to the repository.