473,326 Members | 2,815 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,326 software developers and data experts.

Truncating decimal places in a float (possibly OT)

I have a function that takes a double and truncates it to a specified
number of decimal places. I've found that I have to add a small
number to the input value otherwise I get errors due to the way
floating points work.

double TruncateToDigits(double dValue, int iDigitsToRightOfDecimal)
{
double dEpsilon = 1e-8;
// high limit, about 100,000,000 for this epsilon (1e-8)
// low limit, about 7 decimal places for this epsilon (1e-8)
// modifying it will increase one limit while reducing the other
ASSERT(fabs(dValue) < 100000000.0);
ASSERT(iDigitsToRightOfDecimal <= 7);

int iSignFactor = (dValue >= 0.0 ? 1 : -1);
dValue *= iSignFactor; // make positive
dValue += dEpsilon; // make it error towards the positive
double dMulti = pow(10.0, iDigitsToRightOfDecimal);
dValue *= dMulti; // move valid digits left of decimal
dValue = floor(dValue); // truncate to whole value
dValue /= dMulti; // move digits back
dValue *= iSignFactor; // put sign back
return dValue;
}

This appears to work, however it only reliably works within a certain
range, as listed in the comments.

Is there a better way to do this? One that would work for any
floating point range?
Jul 18 '08 #1
4 7734
Todd wrote:
I have a function that takes a double and truncates it to a specified
number of decimal places. [..]
What does that mean? How would it "truncate" 0.111 to 1 decimal point
when neither 0.111 nor 0.1 can be represented _exactly_ in the binary
system of FP numbers (employed by most computers nowadays)?

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jul 18 '08 #2
On Jul 18, 4:11 pm, Victor Bazarov <v.Abaza...@comAcast.netwrote:
What does that mean? How would it "truncate" 0.111 to 1 decimal point
when neither 0.111 nor 0.1 can be represented _exactly_ in the binary
system of FP numbers (employed by most computers nowadays)?
To be more specific, the input is a fixed decimal place number
(converted to a double) and the output needs to be the floating point
closest to the truncated decimal number. If that makes sense.
Jul 18 '08 #3
Todd wrote:
On Jul 18, 4:11 pm, Victor Bazarov <v.Abaza...@comAcast.netwrote:
>What does that mean? How would it "truncate" 0.111 to 1 decimal
point when neither 0.111 nor 0.1 can be represented _exactly_ in the
binary system of FP numbers (employed by most computers nowadays)?

To be more specific, the input is a fixed decimal place number
(converted to a double) and the output needs to be the floating point
closest to the truncated decimal number. If that makes sense.
The closest you can get in this case is by stopping reading after
the designated digit in the character input. No manipulation with
FP representation required _at_all_. For example, if your input
contains "321.123456" and you need to truncate to 2 digits after
the decimal point, input all digits before the point, then the
point itself, then only 2 digits after the point, you get "321.12"
and then convert that to your internal representation. That's
the best you can do, really.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jul 19 '08 #4
On Jul 18, 2:25*pm, Todd <toddbitr...@gmail.comwrote:
On Jul 18, 4:11 pm, Victor Bazarov <v.Abaza...@comAcast.netwrote:
What does that mean? *How would it "truncate" 0.111 to 1 decimal point
when neither 0.111 nor 0.1 can be represented _exactly_ in the binary
system of FP numbers (employed by most computers nowadays)?

To be more specific, the input is a fixed decimal place number
(converted to a double) and the output needs to be the floating point
closest to the truncated decimal number. *If that makes sense.
How about doing it using strings.

#include <sstream>
#include <string>
#include <iostream>
using namespace std;

double foo( double d, size_t n )
{
stringstream ss;
ss.setf( ios::fixed, ios::floatfield );
ss << d;
n += ss.str().find( '.' ) + 1;
string str = ss.str().substr( 0, n );
stringstream ss2;
ss2 << str;
double d2;
ss2 >d2;

return d2;
}

int main()
{
double d = 1.1234567;
cout << "1 decimal place:" << foo( d, 1 ) << endl;
cout << "2 decimal place:" << foo( d, 2 ) << endl;
cout << "3 decimal place:" << foo( d, 3 ) << endl;
cout << "4 decimal place:" << foo( d, 4 ) << endl;
cout << "5 decimal place:" << foo( d, 5 ) << endl;

return 0;
}
Jul 19 '08 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: Joe M Blow | last post by:
Hi evreyone I just want to kno how to make my value (a float) and round it off to two decimal places Thanks alot Ty
3
by: Brent Bortnick | last post by:
Does anyone know how to find out the number of decimal places a number has. I need this info so that i can round to 3 decimal places if the number has 3 decimal places or to 2 decimal places if...
1
by: Gizmo | last post by:
Hi there i was wondering if any one new to a function that rounds up a float to so many decimal places. I have a number in bytes and converting it to mb's and gb's but once its converted i need to...
5
by: GaryB | last post by:
I have a database field that is the product of a multiply in a sql statement and it sometimes has 5 or more decimal places. I want to truncate beyond the 2nd decimal place(###.##). I figured a...
4
by: Phil Mc | last post by:
OK this should be bread and butter, easy to do, but I seem to be going around in circles and not getting any answer to achieving this simple task. I have numbers in string format (they are...
3
by: cj | last post by:
I want 7 * .105263 to result in an int32 value of 0. and 7 * .189021 to result in an int32 value of 1. I don't want to round. How can I just drop the decimal places?
2
by: prakashdehury | last post by:
can some one pls suggest me why? StreamWriter sw = new StreamWriter(@"c:\Temp\1.txt"); double dd1; double dd2; double dd3; double dd4; dd1 = 1452.123456789876123456; dd2 =...
1
by: Serenityquinn15 | last post by:
Hi! I have a little trouble about in truncating numbers. What i want to do is to get the two decimal places. here's the example: when i try to get the half of 20500.39 it shows like...
2
by: shaleni sen | last post by:
i heard that boolean only takes 3 decimal places eg.7.908 and float takes more than 3 decimal places eg. 7.908766. is this true?
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.