473,732 Members | 1,921 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 TruncateToDigit s(double dValue, int iDigitsToRightO fDecimal)
{
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(dVa lue) < 100000000.0);
ASSERT(iDigitsT oRightOfDecimal <= 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, iDigitsToRightO fDecimal);
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 7764
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...@com Acast.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...@com Acast.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...@gm ail.comwrote:
On Jul 18, 4:11 pm, Victor Bazarov <v.Abaza...@com Acast.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
198995
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
7083
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 the number has 2 decimal places. Any help would be great. Regards, Brent
1
11666
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 be able to do it to 2 decimal places. Thanks for any help Scott.
5
23952
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 Ctype to a decimal value would do that but the four decimal places remain. I found a truncate function but it only truncates to whole numbers. how can I do the truncation? Thanks, G
4
9485
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 coming in from an excel sheet): Examples. 45,666.0041 5664456.12 -5465.25568 ETC
3
1285
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
2069
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 = 1452.123456789123123456; dd3 = 1452.123456789567123456;
1
2653
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 this:10250.195 but what i want to see is 10250.19 only. another one is 20500.42, it shows like this: 10250.2 which in real, it must be 10250.21.
2
3314
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
8944
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8773
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9445
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9180
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
4548
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4805
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3259
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2721
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2177
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.