Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Check if a decimal has more than 3 decimal places?

Tags:

I have a situation that I cannot change: one database table (table A) accepts 6 decimal places, while a related column in a different table (table B) only has 3 decimal places.

I need to copy from A to B, but if A has more than 3 decimal places the extra data will be lost. I cant change the table definition but I can add a workaround. So I'm trying to find out how to check if a decimal has more than 3 decimal places or not?

eg

Table A Id, Qty,  Unit(=6dp) 1,  1,     0.00025 2,  4000,  0.00025  Table B Id, TotalQty(=3dp) 

I want to be able to find out if Qty * Unit from Table A has more than 3 decimals (row 1 would fail, row 2 would pass):

if (CountDecimalPlaces(tableA.Qty * tableA.Unit) > 3) {     return false; } tableB.TotalQty = tableA.Qty * tableA.Unit; 

How would I implement the CountDecimalPlaces(decimal value) {} function?

like image 720
JK. Avatar asked May 23 '11 02:05

JK.


1 Answers

You could compare the value of the number rounded to 3 decimal places with the original value.

if (Decimal.Round(valueDecimal, 3) != valueDecimal) {    //Too many decimals } 
like image 63
RodH257 Avatar answered Sep 23 '22 04:09

RodH257