ECM
ECM
总版主
总版主
  • 社区居民
  • 忠实会员
  • 原创写手
阅读:713回复:0

C# Price Validation using regular expression other way

楼主#
更多 发布于:2016-05-30 21:31
As part of my work,I need to read price values from Excel sheet . I need to implement Prices: Non-numeric characters in Price not allowed price should be valid number for price like int,decimal,double etc like 10,10.00,10,233 valid, -10,-10.00,-10,2333.00 etc are invalid Prices: Price format (dots, comma's, decimals) Zero and negative price values are not allowed Need to check price value type (number type like int,float,decimal etc but will save in database in money format) What datatype I should we choose for Price ? decimal or double or anyother ? In database I took database field type as money.
answer(解决方案):

I do not think you need any regex if you just need to validate price numbers in C#. I'd suggest using Decimal type, here you can find why. The Decimal class contains a static TryParse method that can be used to validate numbers as valid decimal numbers. Here is a slightly modified example from MSDN (I decided to go with InvariantCulture, but it depends on whether your DB contains currencies in EN-US format or not): var validated = false;
decimal number;
// Parse currency value using current culture.
var value = "1,097.63";
var style = System.Globalization.NumberStyles.Number;
var culture = System.Globalization.CultureInfo.InvariantCulture;
if (!Decimal.TryParse(value, style, culture, out number))
    if (number > 0)    // Check if the value is not negative or zero
        validated = true;

 

 

 

 

 

 

 

异常中心网是一家专门收集整理程序员编程过程中遇到的常见异常(exception)以及各种异常问答中心的网站。异常中心网旨在,减少程序员在编码遇到异常,处理各种异常时间和痛苦,让程序员能更愉快的、快速的定位异常并查找对应的异常解决方案。异常中心网诚心打造最完美的编程社区为程序员用户服务,努力成为最好的程序员乐园程序员社区程序异常中心程序bug中心异常问答中心

 

喜欢0 评分0
游客

返回顶部