c# - How can I force an exception if the decimal is larger than the ToString format descriptor? -


i have format decimals using various format descriptors passed code, specify varying # of significant digits left of decimal point. tostring output cannot have many digits on left side per format descriptor or should return error (format overflow).

is there tostring decimal format descriptor (i not find any) or other decimal string conversion mechanism can exception if decimal larger allocated string space left side of decimal? below code throw rather work. i'm hoping more elegant/built in counting characters in format descriptor , figuring out maximum decimal myself , doing compare before attempting conversion. thanks!

    static void main(string[] args)     {         string lformat = null;         decimal lvalue = 123456.5678m;          // example, throw because number not fit 3 significant left side digits...         lformat = "000.00";         console.writeline("format '{0}' value '{1}'.", lformat, lvalue.tostring(lformat));          console.writeline("hit enter exit...");         console.readline();     } 

i don't know of methods have behavior, however, can implement own quite easily. body this;

int significantdigits = 4;   if (myfloat.tostring().split('.')[1].length > significantdigits)     throw new exception("that float high of percision."); 

you'll want refine code (it crash indexoutofrangeexception if entered , int instead of float example) basic idea convert string, split on ., check length of index 1, throw exception if it's greater limit.


Comments

Popular posts from this blog

ios - UICollectionView Self Sizing Cells with Auto Layout -

node.js - ldapjs - write after end error -

DOM Manipulation in Wordpress (and elsewhere) using php -