473,796 Members | 2,460 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Alternative to Decimal type

Hi all

I have a standard requirement for a 'decimal' type, to instantiate and
manipulate numeric data that is stored in a database. I came up with a
solution long before the introduction of the Decimal type, which has
been working well for me. I know the 'scale' (number of decimal
places) of the number in advance. When I read the number in from the
database I scale it up to an integer. When I write it back I scale it
down again. All arithmetic is done using integers, so I do not lose
accuracy.

There is one inconvenience with this approach. For example, if I have
a product quantity with a scale of 4, and a price with a scale of 2,
and I want to multiply them to get a value with a scale of 2, I have
to remember to scale the result down by 4. This is a minor chore, and
errors are quickly picked up by testing, but it does make the code a
bit messy, so it would be nice to find a solution.

I am now doing some refactoring, and decided to take a look at the
Decimal type. My initial impressions are that it is quite awkward to
use, that I do not need its advanced features, and that it does not
help solve the one problem I have mentioned above.

I therefore spent a bit of time experimenting with a Number type that
suits my particular requirements. I have come up with something that
seems to work, which I show below.

I have two questions.

1. Are there any obvious problems in what I have done?

2. Am I reinventing the wheel unnecessarily? i.e. can I do the
equivalent quite easily using the Decimal type?

--------------------
from __future__ import division

class Number(object):
def __init__(self,v alue,scale):
self.factor = 10.0**scale
if isinstance(valu e,Number):
value = value.value / value.factor
self.value = long(round(valu e * self.factor))
self.scale = scale

def __add__(self,ot her):
if isinstance(othe r,Number):
other = other.value / other.factor
return Number((self.va lue/self.factor)+ot her,self.scale)

def __sub__(self,ot her):
if isinstance(othe r,Number):
other = other.value / other.factor
return Number((self.va lue/self.factor)-other,self.scal e)

def __mul__(self,ot her):
if isinstance(othe r,Number):
other = other.value / other.factor
return Number((self.va lue/self.factor)*ot her,self.scale)

def __truediv__(sel f,other):
if isinstance(othe r,Number):
other = other.value / other.factor
return Number((self.va lue/self.factor)/other,self.scal e)

def __radd__(self,o ther):
return self.__add__(ot her)

def __rsub__(self,o ther):
return Number(other-(self.value/self.factor),se lf.scale)

def __rmul__(self,o ther):
return self.__mul__(ot her)

def __rtruediv__(se lf,other):
return Number(other/(self.value/self.factor),se lf.scale)

def __cmp__(self,ot her):
if isinstance(othe r,Number):
other = other.value / other.factor
this = self.value / self.factor
if this < other:
return -1
elif this other:
return 1
else:
return 0

def __str__(self):
s = str(self.value)
if s[0] == '-':
minus = '-'
s = s[1:].zfill(self.sca le+1)
else:
minus = ''
s = s.zfill(self.sc ale+1)
return '%s%s.%s' % (minus, s[:-self.scale], s[-self.scale:])
--------------------

Example usage -
>>>qty = Number(12.5,4)
price = Number(123.45,2 )
>>>print price * qty
1543.13 [scale is taken from left-hand operand]
>>>print qty * price
1543.1250 [scale is taken from left-hand operand]
>>>print Number(qty * price,2)
1543.13 [scale is taken from Number instance]
--------------------

At this stage I have not built in any rounding options, but this can
be done later if I find that I need it.

Any comments will be welcome.

Thanks

Frank Millman
Jun 27 '08
12 2174
In article <f7************ *************** *******@25g2000 hsx.googlegroup s.com>,
Frank Millman <fr***@chagford .comwrote:
>
My approach is based on expressing a decimal number as a combination
of an integer and a scale, where scale means the number of digits to
the right of the decimal point.
You should probably use one written by an expert:

http://www.pythoncraft.com/FixedPoint.py
--
Aahz (aa**@pythoncra ft.com) <* http://www.pythoncraft.com/

"as long as we like the same operating system, things are cool." --piranha
Jun 27 '08 #11
On Jun 11, 11:48*am, Frank Millman <fr...@chagford .comwrote:
Thanks to all for the various replies. They have all helped me to
refine my ideas on the subject. These are my latest thoughts.
[snip]
>
My main concern is that my approach may be naive, and that I will run
into situations that I have not catered for, resulting in errors. If
this is the case, I will drop this like a hot potato and stick to the
Decimal type. Can anyone point out any pitfalls I might be unaware of?

I will be happy to show the code for the new Number class if anyone is
interested.
Thanks again for all the really useful replies.

I will have a look at gmpy, and I will study FixedPoint.py closely.

Frank
Jun 27 '08 #12
On 2008-06-12, Dennis Lee Bieber <wl*****@ix.net com.comwrote:
If you were to follow the footsteps of COBOL, you'd be using
BCD internally, with a special code to represent the decimal
point (and maybe, to save space, the sign too)

Old mainframes had instructions to work with packed BCD as a
register format (the Xerox Sigma series used four 32-bit
registers to represent a 31 digit packed BCD number). Okay, I
think even the Pentium's still have a BCD operation set,
IIRC, most general purpose microprocessors I've used had
special instructions to make packed BCD operations easier, and
back in the day (when Pascal was much more popular than C)
compilers for microprocessors usually offered a BCD floating
point data type.

--
Grant Edwards grante Yow! The SAME WAVE keeps
at coming in and COLLAPSING
visi.com like a rayon MUU-MUU ...
Jun 27 '08 #13

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

Similar topics

21
4540
by: Batista, Facundo | last post by:
Here I send it. Suggestions and all kinds of recomendations are more than welcomed. If it all goes ok, it'll be a PEP when I finish writing/modifying the code. Thank you. .. Facundo
7
2033
by: Blake T. Garretson | last post by:
I'm having some issues with decimal.Decimal objects playing nice with custom data types. I have my own matrix and rational classes which implement __add__ and __radd__. They know what to do with Decimal objects and react appropriately. The problem is that they only work with Decimals if the custom type is on the left (and therefore __add__ gets called), but NOT if the Decimal is on the left. The Decimal immediately throws the usual...
17
6154
by: John Bentley | last post by:
John Bentley: INTRO The phrase "decimal number" within a programming context is ambiguous. It could refer to the decimal datatype or the related but separate concept of a generic decimal number. "Decimal Number" sometimes serves to distinguish Base 10 numbers, eg "15", from Base 2 numbers, Eg "1111". At other times "Decimal Number" serves to differentiate a number from an integer. For the rest of this post I shall only use either...
6
30032
by: Gilgamesh | last post by:
Is decimal type a good choice to use for storing currency? I've got a situation that when I store 8.50 in a decimal type variable and read it back, I'm getting 8.5. Is there a better data type to store currency? Thanks, Gilgamesh
43
6902
by: Mountain Bikn' Guy | last post by:
I have a situation where an app writes data of various types (primitives and objects) into a single dimensional array of objects. (This array eventually becomes a row in a data table, but that's another story.) The data is written once and then read many times. Each primitive read requires unboxing. The data reads are critical to overall app performance. In the hopes of improving performance, we have tried to find a way to avoid the...
15
12828
by: Kay Schluehr | last post by:
I wonder why this expression works: >>> decimal.Decimal("5.5")**1024 Decimal("1.353299876254915295189966576E+758") but this one causes an error 5.5**1024 Traceback (most recent call last):
8
9566
by: Gilbert Fine | last post by:
This is a very strange exception raised from somewhere in our program. I have no idea how this happen. And don't know how to reproduce. It just occurs from time to time. Can anyone give me some suggestion to fix this? Thanks. -- Gilbert
25
3038
by: Lennart Benschop | last post by:
Python has had the Decimal data type for some time now. The Decimal data type is ideal for financial calculations. Using this data type would be more intuitive to computer novices than float as its rounding behaviour matches more closely what humans expect. More to the point: 0.1 and 0.01 are exact in Decimal and not exact in float. Unfortunately it is not very easy to access the Decimal data type. To obtain the decimal number 12.34 one...
0
28076
Frinavale
by: Frinavale | last post by:
Convert a Hex number into a decimal number and a decimal number to Hex number This is a very simple script that converts decimal numbers into hex values and hex values into decimal numbers. The example following this one demonstrates how to convert decimal numbers into binary values. A hex number is a string that contains numbers between 0-9 and characters A-F; where A = 10, B = 11, ..., F = 15. (For more information please look up...
0
9683
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
9529
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
10457
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
10231
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10176
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9054
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6792
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4119
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
3
2927
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.