कैसे toString फ़ंक्शन का उपयोग और उसके बाद के बारे में दशमलव बिंदु पर विभाजित है, अर्थात्:
[संपादित करें] त्वरित छोटे वर्ग/विधि परीक्षण करने के लिए:
public class Test
{
public struct FractionSplit
{
public int BeforeDecimal;
public int AfterDecimal;
}
public FractionSplit SplitDecimal(decimal decimalValue,
int decimalPrecision = 2)
{
// now do the split - the apres decimal precision defined by
// the format function which defaults to 2 places i.e. "0.00"
string splitValue = decimalValue.ToString(string.Format("0.{0}",
new String('0', decimalPrecision)), CultureInfo.InvariantCulture);
string[] splitParts = splitValue.Split('.');
// now factor out derived splits as ints into struct
var fractionSplit = new FractionSplit
{
BeforeDecimal = int.Parse(splitParts[0]),
AfterDecimal = int.Parse(splitParts[1])
};
return fractionSplit;
}
}
उपयोग:
Test test = new Test();
var result = test.SplitDecimal(12.1m);
प्रति दान की इस टिप्पणी के रूप में, यह वास्तव में यह निष्कर्ष निकाल जाएगा 12.1 रिटर्न 12 और 10 है, जिसके परिणामस्वरूप पूर्णांक के रूप में है। क्या यह सही है?? - कौन जानता है, लेकिन अब उस मामले का उपयोग बंद कर देता है। यह ToString ("0. {0}") भाग के कारण है, जो डिफ़ॉल्ट रूप से किसी भी दशमलव भाग के अंत में '0' जोड़ता है जिसमें केवल एक अंक होता है।
स्रोत
2012-05-22 12:54:44
एक बेहतर तरीका नहीं हो सकता है सब पर एक दशमलव उपयोग करने के लिए, लेकिन एक 'int' /' long' का प्रतिनिधित्व "अपने मूल्य 100 से गुणा" का उपयोग । – Rawling
असामान्य मूल्यों से सावधान रहें। दशमलव के लिए अधिकतम मान ~ 7.9e28 है। Int के लिए अधिकतम मान ~ 2e9 (काफी छोटा) है। यहां तक कि केवल ~ 9e18 तक जाता है। तो यदि आप जानते हैं कि मान हमेशा> = 0 होगा, तो आप एक उलंग का उपयोग कर सकते हैं जो ~ 18e18 तक जाता है, जिससे थोड़ा अधिक छूट मिलती है। – Davio
इसी तरह के प्रश्न के उत्तर के उत्तर में उन हिस्सों को आंशिक भाग के लिए उपयुक्त हो सकता है: http://stackoverflow.com/a/13038524/1178314 –