I am consuming a web service in C# and inserting the records into a postgres database via the Npgsql library.

I have a cost field that the web service gives me as a decimal type "12.57" my postgres database and application expect it to be a fixed 6 digit number of a BigInt type like "125700"

I cannot think of a great way to do this other than something like convert it to a string, remove the decimal pad a few 0's and convert to an Int64.

Am I missing a simpler way?

Edit: I should add that currently I use an Npgsql parameter type of BigInt and when I feed it the cost, it is just rounding 12.57 to 13 in the database

有帮助吗?

解决方案

Why not just multiply by 10000?

其他提示

If you want to preserve the cost values with 2 digits after the decimal point, multiply the value by 100 before storing it in the database.

string cost = "12.57";
decimal d = decimal.Parse(cost);
if (d >= 10000.0m)
{
    throw new Exception("Input value " + cost + " is too large");
}
int i = (int)(d * 100.0m + 0.5m);
string result = i.ToString();

The + 0.5m will round the value in case there are more than 2 digits after the decimal point.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top