There are functions available for doing exactly that, but they can depend on what language you use. Two examples:
-
if you have access to a decent C99 math library, you can use
nextafter
(and its float and long double variants,nextafterf
andnextafterl
); or thenexttoward
family (which take a long double as second argument). -
if you write Fortran, you have the
nearest
intrinsic available
If you can’t access these directly from your language, you can also look at how they’re implemented in freely available, such as this one.