You need to sign in to do that
Don't have an account?
Math Function
can someone please explain to me how this code is conerting String to word. I would apprecite you rhelp.Thanks
//Takes a Number as a String, and makes it into the word number. public String toWords(String s){ String[] th = new String[]{'','thousand','million', 'billion','trillion'}; String[] dg = new String[]{'zero','one','two','three','four', 'five','six','seven','eight','nine'}; String[] tn = new String[]{'ten','eleven','twelve','thirteen', 'fourteen','fifteen','sixteen', 'seventeen','eighteen','nineteen'}; String[] tw = new String[]{'twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety'}; s = s.replace(',',''); Integer x = 0; x = s.indexOf('.'); if (x == -1) x = s.length(); if (x > 15) return 'too big'; String[] qr = s.split(''); Integer[] n = new Integer[0]; for (Integer i=1;i < qr.size();i++){ n.add(Integer.valueOf(qr[i])); } String str = ''; Integer sk = 0; for (Integer i=0; i < x; i++) { if (math.mod(x-i,3)==2){ if (n[i] == 1) { str += tn[n[i+1]] + ' '; i++; sk=1; } else if (n[i]!=0) { str += tw[n[i]-2] + ' '; sk=1; } } else if (n[i]!=0) { str += dg[n[i]] +' '; if(math.mod(x-i,3)==0) str += 'hundred '; sk=1; } if(math.mod(x-i,3)==1){ if (sk==1) str += th[(x-i-1)/3] + ' '; sk=0; } } if (x != s.length()) { Integer y = s.length(); str += 'point '; for (Integer i=x+1; i<y; i++) str += dg[n[i]] +' '; } return str; }
Yeah, that's a bit tough to read -- but still nothing compared to the massively insane logic some of the Scientific Computing folks write.
Unfortunately, what constitutes good optimization on traditional platforms can be extremely counter-productive in Apex, since the REAL bottleneck here is # of script statements -- and sometimes, stack depth -- and rarely, heap size.
Here's my first rough stab at a slightly more human-readable Apex version of "number wordify" -- clearly it can be refined, optimized, and cleaned up further:
--
Mike
Steve, Thanks for the elaborate explanation. Though i am still trying to understand, it is indeed more readable.
The name is Mike :)
Feel free to ask about the details of a specific piece.