1 33 package smallsql.database; 34 35 import java.math.*; 36 37 public class Money extends Number implements Mutable{ 38 39 42 private static final long serialVersionUID = -620300937494609089L; 43 long value; 44 45 46 49 private Money(){} 50 51 52 public Money(double value){ 53 this.value = (long)(value * 10000); 54 } 55 56 public Money(float value){ 57 this.value = (long)(value * 10000); 58 } 59 60 61 public static Money createFromUnscaledValue(long value){ 62 Money money = new Money(); 63 money.value = value; 64 return money; 65 } 66 67 public static Money createFromUnscaledValue(int value){ 68 Money money = new Money(); 69 money.value = value; 70 return money; 71 } 72 73 public int intValue() { 74 return (int)(value / 10000.0); 75 } 76 public float floatValue() { 77 return value / 10000.0F; 78 } 79 public double doubleValue() { 80 return value / 10000.0; 81 } 82 public long longValue() { 83 return (long)(value / 10000.0); 84 } 85 86 public String toString(){ 87 StringBuffer buffer = new StringBuffer (); 88 buffer.append(longValue()).append('.'); 89 final long v = Math.abs(value); 90 buffer.append( (char)((v % 10000) / 1000 + '0') ); 91 buffer.append( (char)((v % 1000) / 100 + '0') ); 92 buffer.append( (char)((v % 100) / 10 + '0') ); 93 buffer.append( (char)((v % 10) + '0') ); 94 95 return buffer.toString(); 96 } 97 98 public boolean equals(Object obj){ 99 return (obj instanceof Money && ((Money)obj).value == value); 100 } 101 102 public int hashCode(){ 103 return (int)(value ^ (value >>> 32)); 104 } 105 106 public long unscaledValue(){ 107 return value; 108 } 109 110 public static long parseMoney( String str ){ 111 return Utils.doubleToMoney(Double.parseDouble( str )); 113 } 114 115 private byte[] toByteArray(){ 116 byte[] bytes = new byte[8]; 117 118 int offset = 0; 119 bytes[offset++] = (byte)(value >> 56); 120 bytes[offset++] = (byte)(value >> 48); 121 bytes[offset++] = (byte)(value >> 40); 122 bytes[offset++] = (byte)(value >> 32); 123 bytes[offset++] = (byte)(value >> 24); 124 bytes[offset++] = (byte)(value >> 16); 125 bytes[offset++] = (byte)(value >> 8); 126 bytes[offset++] = (byte)(value); 127 return bytes; 128 } 129 130 public BigDecimal toBigDecimal(){ 131 if(value == 0) return ZERO; 132 return new BigDecimal( new BigInteger( toByteArray() ), 4 ); 133 } 134 135 136 public Object getImmutableObject(){ 137 return toBigDecimal(); 138 } 139 140 static private final BigDecimal ZERO = new BigDecimal("0.0000"); 141 } | Popular Tags |