By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,227 Members | 1,288 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,227 IT Pros & Developers. It's quick & easy.

Weird result of calculation after casting to float

P: n/a
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::ostringstream 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?

--
Matthias Kaeppler
Jul 23 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
Matthias Kaeppler wrote:
[...]
What is happening here?

Take a look at 'fixed' manipulator.
Jul 23 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.