Weird result of calculation after casting to float

M

Matthias Kaeppler

Hello,

this is related to another post by me, which sort went down, so I
thought I'd make a new thread.
My problem is, I want to display file sizes in the format X.YZ (two
digits behind the dot). I use a stringstream to do the formatting:

Here's my attempt to create a string holding file sizes this way:

Glib::ustring FileBrowser::get_file_size( const boostfs::path& path )
{
std::eek:stringstream sstream;
sstream.precision( 2 );

try
{
if( boostfs::is_directory(path) )
return "0";

boost::intmax_t size = boostfs::file_size( path );

if( size >= GIGA_BYTE )
{
sstream << (static_cast<float>(size) / GIGA_BYTE);
sstream << " GB";
}
else if( size >= MEGA_BYTE )
{
sstream << (static_cast<float>(size) / MEGA_BYTE);
sstream << " MB";
}
else if( size >= KILO_BYTE )
{
sstream << (static_cast<float>(size) / KILO_BYTE);
sstream << " KB";
}
else
{
sstream << size;
sstream << " B";
}
}
catch( const boostfs::filesystem_error& e )
{
std::cerr << e.what() << std::endl;
}

return sstream.str();
}

The problem:
Sometimes, the result of this division is garbage, e.g. 1.7e+02 (when
the file is actually just a couple of KB large). This doesn't happen if
I don't cast to float.
I'm always dividing by sane numbers; the constants are defined like this:

const int KIBI_BYTE = 1024;
const int MEBI_BYTE = KIBI_BYTE * 1024;
const int GIBI_BYTE = MEBI_BYTE * 1024;

const int KILO_BYTE = 1000;
const int MEGA_BYTE = KILO_BYTE * 1000;
const int GIGA_BYTE = MEGA_BYTE * 1000;

What is happening here?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,968
Messages
2,570,153
Members
46,699
Latest member
AnneRosen

Latest Threads

Top