16.3 Determining Net Charge on a Molecule

The total (or net) charge on a molecule can be conveniently calculated by calling OEChem's OENetCharge function on a molecule. If any of the atoms in the molecule has a non-zero partial charge, i.e. the function OEHasPartialCharges returns true, this function returns the sum of the partial charges rounded to the nearest integer. If the molecule doesn't have partial charges, this function returns the sum of the formal charges on each atom.

This logic should return the total charge on the molecule if either formal or partial charges are present. When both partial and formal charges are present, partial charges take priority. For ``valid'' partial charges, the sum of the partial charges should always be an integer equal the sum of the formal charges, so this preference typically won't matter. However when reading from file formats that contain partial charges, such as .mol2 or Delphi PDB, OEChem may be unable to correctly assign formal charges to each atom, in which case the partial charges are often more trustworthy.

The following example contains two functions that determines whether a molecule is a cation or anion, i.e. carries a formal positive or negative charge respectively.

void MyIsCation(const OEMolBase &mol)
{
  return OENetCharge(mol) > 0;
}

void MyIsAnion(const OEMolBase &mol)
{
  return OENetCharge(mol) < 0;
}