views:

146

answers:

1

Hello,

Today's problem is as follows: we have a table in an Oracle database. The table contains a field that is of the type Number(18, 3).

On the surface, both saving and loading data from said field work perfectly. However, further inspection reveals, that numbers that have three decimal digits in them, e.g. 500.001, are read from the database in such a way that the string representation of the decimal has a fourth, zero digit (e.g. 500.0010). This seems to happen whenever the third decimal digit is nonzero.

For math purposes, this is not a problem. However, we have validators that verify the number of decimal digits in a decimal number by converting it to a string and then counting the number of decimal digits. Since this particular piece of data is defined to have at most three decimal digits, the extra zero causes a validation error.

Since I can't change the validators, I'm left wondering if there is a clean way to get the decimal without the extra zero, apart from converting the number to a string, trimming the trailing zeroes and then re-parsing it? Or should I be doing something different altogether?

+2  A: 

Try this:

decimal trimmed = ((decimal)((int)(number * 1000))) / 1000

Casting to int gets rid of the fractional part. You don't need all the parentheses but I think it's easier to see what's going on if the order of operations is explictily indicated.

DrJokepu
That looks like it will work, yes. I was sort of hoping there would be a magical way to tell the driver to get me the value the way I want it, so I could avoid doing that. But unless such a way turns up, I'll probably pick this option. :-)
Rytmis