Skip to content

Instantly share code, notes, and snippets.

@doshiraki
Last active April 17, 2023 22:38
Show Gist options
  • Select an option

  • Save doshiraki/31e81421fb270fb84d2f335eceb77fb1 to your computer and use it in GitHub Desktop.

Select an option

Save doshiraki/31e81421fb270fb84d2f335eceb77fb1 to your computer and use it in GitHub Desktop.
Valid Size Number Format in C++.
#include <ios>
#include <iostream>
#include <iomanip>
#include <limits>
template <typename _NumberT>
class ValidNumberFmt
{
_NumberT n;
public:
inline ValidNumberFmt(_NumberT n)
{
this->n = n;
}
inline _NumberT getPrecision() const
{
return std::numeric_limits<_NumberT>::digits10;
}
inline _NumberT getValue() const
{
return n;
}
};
template <typename _CharT, typename _Traits, typename _NumberT>
inline std::basic_ostream<_CharT, _Traits> &operator<<(std::basic_ostream<_CharT, _Traits> &__base, const ValidNumberFmt<_NumberT> nos)
{
return __base << std::defaultfloat << std::setprecision(nos.getPrecision()) << nos.getValue();
}
int main(int argc, char *argv[])
{
std::cout << ValidNumberFmt(12345678901) << "\t" << ValidNumberFmt(1.2345678901234567) << "\t" << ValidNumberFmt(1.2345678f);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment