1 23 24 package org.infoglue.deliver.util; 25 26 import java.text.DecimalFormat ; 27 import java.text.NumberFormat ; 28 import java.util.Locale ; 29 import java.util.Random ; 30 31 36 37 public class MathHelper 38 { 39 40 43 public int hexToDecimal(String hex) 44 { 45 return new Integer (Integer.parseInt(hex,16)).intValue(); 46 } 47 48 51 52 public String fileSize(long size) 53 { 54 return fileSize(size, Locale.getDefault()); 55 } 56 57 public String fileSize(long size, Locale locale) 58 { 59 String [] pfix = { "byte", "Kb", "Mb", "Gb" }; 60 double c = new Long (size).doubleValue(); 61 int cnt=0; 62 63 while (c > 512 && cnt < 3) { 64 c /= 1024; cnt++; 65 } 66 67 NumberFormat nf = NumberFormat.getInstance(locale); 68 if(c > 9) nf.setMaximumFractionDigits(0); else nf.setMaximumFractionDigits(2); 69 70 return nf.format(c) + " " + pfix[cnt]; 71 } 72 73 77 public Integer stringToInteger(String value) 78 { 79 if(value == null) 80 return null; 81 82 return new Integer (Integer.parseInt(value)); 83 } 84 85 89 public Integer floatStringToInteger(String value) 90 { 91 if(value == null) 92 return null; 93 94 return new Integer (new Float (value).intValue()); 95 } 96 97 101 public Float floatStringToFloat(String value) 102 { 103 if(value == null) 104 return null; 105 106 return new Float (value); 107 } 108 109 113 114 public String getNumberAsString(Object value, Locale locale, String pattern) 115 { 116 NumberFormat nf = NumberFormat.getNumberInstance(locale); 117 DecimalFormat df = (DecimalFormat )nf; 118 df.applyPattern(pattern); 119 String output = df.format(value); 120 return output; 121 } 122 123 127 128 public String getNumberAsString(Object value, String pattern) 129 { 130 NumberFormat nf = NumberFormat.getNumberInstance(); 131 DecimalFormat df = (DecimalFormat )nf; 132 df.applyPattern(pattern); 133 String output = df.format(value); 134 return output; 135 } 136 137 140 141 public Float divide(Float value, int divider) 142 { 143 if(value == null) 144 return null; 145 146 return new Float (value.floatValue() / divider); 147 } 148 149 150 153 154 public int getRandom() 155 { 156 Random generator = new Random (); 157 return generator.nextInt(); 158 } 159 160 163 164 public int getRandom(int upperLimit) 165 { 166 Random generator = new Random (); 167 return generator.nextInt(upperLimit); 168 } 169 170 173 174 public int round(float floatNumber) 175 { 176 return (int)Math.round(floatNumber); 177 } 178 179 180 183 184 public float multiply(Number first, Number second) 185 { 186 return first.floatValue() * second.floatValue(); 187 } 188 189 192 193 public float multiply(float first, float second) 194 { 195 return first * second; 196 } 197 198 201 202 public float divide(Number first, Number second) 203 { 204 return first.floatValue() / second.floatValue(); 205 } 206 207 210 211 public float divide(float first, float second) 212 { 213 return first / second; 214 } 215 } 216 | Popular Tags |