A case study of C # translation of the Chinese function of currency digital conversion based on the pure mathematics recursive method in detail

Source: Internet
Author: User
This article mainly introduces C # based on the pure mathematical method recursive implementation of currency digital conversion Chinese function, involving C # for string traversal, conversion and mathematical operations related operation skills, the need for friends can refer to the following

In this paper, we describe the function of C # Recursive implementation of Chinese currency digital conversion based on pure mathematical method. Share to everyone for your reference, as follows:

Recently because of the project, the need to write a currency number conversion Chinese algorithm, first in the net to find a bit, the results found that no column is replaced with (replace) the way to achieve, so want to write a different algorithm, because I was learning mathematics, so the method of pure mathematics to achieve.

Note: the algorithm in this article supports conversion of currency numbers less than 1023 (i.e. 999.9 billion trillion).

Chinese note: Before explaining the code, let's review the method of currency reading first.

10020002.23 reading for the first 0 of the Zero II three
1020 reading for the first 0 and the whole.
100000 read for pickup million whole
0.13 read as one corner three points

Code:

Test Engineering

static void Main (string[] args) {Console.WriteLine ("Enter Amount"); string inputnum = Console.ReadLine (); while (inputnum! = " Exit ") {//currency digital conversion class Numcast NC = new Numcast (), if (NC. Isvalidated<string> (Inputnum)) {try{string Chinesecharacter = NC. Converttochinese (Inputnum); Console.WriteLine (Chinesecharacter);} catch (Exception er) {Console.WriteLine (Er. Message);}} Else{console.writeline ("Illegal numbers or formats");} Console.WriteLine ("\ n Please enter Amount"); inputnum = Console.ReadLine ();} Console.ReadLine ();}

Introduction to the function of currency conversion class (Numcast Class)

1. Provisions of constants

<summary>///digits//</summary>public enum Numlevel {Cent, Chiao, Yuan, Ten, Hundred, Thousand, Tenthousand , Hundredmillon, trillion};///<summary>///digit index///</summary>private int[] numlevelexponent = new int[] {-  2,-1, 0, 1, 2, 3, 4, 8,};///<summary>///Chinese characters//</summary>private string[] numleverchinesesign = new String[] {"Min", "Jiao", "Yuan", "Pick", "Bai", "Qian", "million", "billion", "mega"};///<summary>///uppercase///</summary>private string[] Numchinesecharacter = new string[] {"0", "one", "II", "three", "Restaurant", "WU", "Lu", "Qi", "ba", "JIU"};///<summary>///Whole (when no corner ticks)///< /summary>private Const string endofint = "integer";

2. Verification of digital legitimacy using regular expression validation

<summary>///Regular expression verifies whether the number is legal///</summary>///<param name= "Num" ></param>///<returns> </returns>public bool Isvalidated<t> (T Num) {regex reg = new Regex (@ "^ ([0]) | ( [1-9]\d{0,23})) (\.\d{1,2}), ($ "), if (Reg. IsMatch (Num.tostring ())) {return true;} return false;}

3. Get digital digits such as 1000 for Numlevel.thousand

<summary>///get digital digits using log///</summary>///<param name= "Num" ></param>///<returns> </returns>private numlevel getnumlevel (double Num) {double numlevellength; Numlevel nlvl = new Numlevel (), if (num > 0) {numlevellength = Math.floor (num)), for (int i = math.log10. Length-1; I >= 0; i--) {if (numlevellength >= numlevelexponent[i]) {nlvl = (numlevel) I;break;}}} ELSE{NLVL = Numlevel.yuan;} return NLVL;}

4. Determine if there is a jump between the numbers, that is, whether to add 0 in the middle of the Chinese, for example 1020 should be added 0.

<summary>///whether to jump///</summary>///<returns></returns>private bool IsDumpLevel (double Num {if (num > 0) {numlevel? currentlevel = Getnumlevel (num); Numlevel? Nextlevel = Null;int Numexponent = this. numlevelexponent[(int) currentlevel];d ouble Postfixnun = Math.Round (Num% (Math.pow (numexponent)), 2); if ( postfixnun> 0) Nextlevel = getnumlevel (Postfixnun); if (currentlevel! = NULL && Nextlevel! = null) {if (currentle Vel > nextlevel + 1) {return true;}}} return false;}

5. Divide the long digits into two smaller arrays of numbers , for example 999.9 billion megabytes, divided into 999.9 billion and 0 megabytes, because the computer does not support too long numbers.

Whether the <summary>///is greater than the trillion, if greater than the string is divided into two parts,////part is the previous number of megabytes///or the other part is the number of megabytes///</summary>///<param name= "Num" ></param>///<returns></returns>private bool Isbigthantillion (string Num) {bool IsBig = false;if ( Num.indexof ('. ')! =-1) {//if greater than Num.indexof ('. ') > numlevelexponent[(int) numlevel.trillion]) {IsBig = true;}} else{//if greater than (Num.length > numlevelexponent[(int) numlevel.trillion]) {IsBig = true;}} return IsBig;} <summary>///the number string from ' Mega ' two///</summary>///<returns></returns>private double[] Splitnum (String Num) {//Gigabit start bit double[] tillionlevelnums = new Double[2];int trillionlevellength;if (Num.indexof ('. ') = =- 1) trillionlevellength = num.length-numlevelexponent[(int) numlevel.trillion];elsetrillionlevellength = Num.IndexOf ( '.') -numlevelexponent[(int) numlevel.trillion];//more than the number tillionlevelnums[0] = convert.todouble (num.substring (0, trillionlevellength));//megabits below tillionlevelnums[1] = convert.todouble (num.substring (trillionlEvellength)); return tillionlevelnums;} 

6. If you want to start with "one pick", you can change it to "pick up"

BOOL Isstartoften = false;while (num >=10) {if (num = =) {Isstartoften = True;break;} Num's digit Numlevel currentlevel = getnumlevel (num); int numexponent = this. numlevelexponent[(int) currentlevel]; Num = Convert.ToInt32 (Math.floor (Num/math.pow, numexponent)); if (CurrentLevel = = Numlevel.ten && Num = = 1) {i Sstartoften = True;break;}} return isstartoften;

7. Merge a currency string that is larger than the number of megabytes converted into

<summary>///Merge separate array Chinese currency character////</summary>///<param name= "Tillionnums" ></param>///< Returns></returns>private string Contactnumchinese (double[] tillionnums) {string uptillionstr = Calculatechinesesign (Tillionnums[0], numlevel.trillion, True, Isstartoften (Tillionnums[0])); string downtrillionStr = Calculatechinesesign (tillionnums[1], NULL, true,false); string chinesecharactor = String. empty;//If the character is separated by a skip if (Getnumlevel (tillionnums[1] *) = = numlevel.trillion) {chinesecharactor = Uptillionstr + numleverchinesesign[(int) numlevel.trillion] + downtrillionstr;} Else{chinesecharactor = uptillionstr + numleverchinesesign[(int) numlevel.trillion];if (downtrillionstr! = "0-dollar whole") { Chinesecharactor + = numchinesecharacter[0] + downtrillionstr;} Else{chinesecharactor + = "meta-integer";}} return chinesecharactor;}

8. Recursive calculation of currency numbers in Chinese

<summary>///Calculating Chinese strings///</summary>///<param name= "Num" > Digital </param>///<param name= "NL" > Digital level such as 10 million of the digital level is million </param>///<param name= "Isexceptten" > whether to start with ' one pick ' </param>///<returns > Chinese capital </returns>public string calculatechinesesign (double Num, numlevel?) NL, bool Isdump,bool isexceptten) {num = Math.Round (num, 2); bool isdump = false;//num digit numlevel? currentlevel = Getnumleve L (Num); int numexponent = this. numlevelexponent[(int) currentlevel];string Result = string. empty;//the result of an int prefixnum;//remainder when it is fractional, the numerator denominator is multiplied by 100double Postfixnun; if (Num >= 1) {prefixnum = Convert.ToInt32 ( Math.floor (Num/math.pow (numexponent)));p Ostfixnun = Math.Round (Num% (Math.pow (numexponent)), 2);} Else{prefixnum = Convert.ToInt32 (Math.floor (Num*100/math.pow (Ten, numexponent+2)));p Ostfixnun = Math.Round (Num * 100 ( Math.pow (Ten, numexponent + 2)), 2);p Ostfixnun *= 0.01;} if (Prefixnum < 10) {//Avoid starting with ' one pick ' if (! ( numchinesecharacter[(int) prefixnum] = = Numchinesecharacter[1]&& CurrentLevel = = Numlevel.ten && isexceptten) {Result + = numchinesecharacter[( int) prefixnum];} Else{isexceptten = false;} Add the unit if (currentlevel = = Numlevel.yuan) {////when the "meta" bit is not zero plus "meta". if (NL = = null) {result + = numleverchinesesign[(int) currentlevel];//When the decimal point is zero plus "whole" if (Postfixnun = = 0) {result + = Endofint;} }}else{result + = numleverchinesesign[(int) currentlevel];}//When the true digit is zero plus "meta" if (NL = = null && Postfixnun < 1 &am p;& currentlevel > Numlevel.yuan && postfixnun > 0) {Result + = numleverchinesesign[(int) Numlevel.yuan] ;}} else{//the current prefix number is not removed, recursion goes down numlevel? NEXTNL = null;if ((int) currentlevel >= (int) (numlevel.tenthousand)) nextnl = CurrentLevel; Result + = Calculatechinesesign ((double) prefixnum, NEXTNL, Isdump, Isexceptten), if ((int) currentlevel >= (int) ( Numlevel.tenthousand) {Result + = numleverchinesesign[(int) currentlevel];}} Whether to jump bit//to determine whether to add 0, such as 302 will give 300 after adding 0, into 302. if (Isdumplevel (Num)) {Result + = Numchinesecharacter[0];isDump = true;} Whether the remainder requires recursion if (Postfixnun > 0) {Result + = Calculatechinesesign (Postfixnun, NL, Isdump, false);} else if (Postfixnun = = 0 && currentlevel > Numlevel.yuan) {//When the number is a 0-dollar end plus a meta-integer such as 10,000,001,000,000-yuan integer if (NL = = null) {ResU Lt + = numleverchinesesign[(int) Numlevel.yuan]; Result + = Endofint;}} return Result;}

9. The conversion method of the external call.

<summary>///conversion method for external calls///</summary>///<param name= "Num" ></param>///<returns> </returns>public string Converttochinese (String Num) {if (! Isvalidated<string> (Num)) {throw new OverflowException ("The numeric format is incorrect, please enter a number less than 999.9 billion trillion and the maximum amount of accurate cent!") ");} String chinesecharactor = String. EMPTY;IF (isbigthantillion (num)) {double[] tillionnums = splitnum (num); chinesecharactor = Contactnumchinese ( Tillionnums);} Else{double dnum = convert.todouble (Num); chinesecharactor = Calculatechinesesign (Dnum, NULL, True, Isstartoften (DNum)) ;} return chinesecharactor;}

Summary:

Personally, the soul of the program is the algorithm, large to a system of business logic, small to a currency number to Chinese algorithm, everywhere embodies a logic idea.

Whether the requirements can be abstracted into a good mathematical model is directly related to the complexity and stability of the program implementation. In some commonly used functions to think of a different algorithm, it is very helpful for us to develop ideas.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.