001 package org.bukkit.util; 002 003 /** 004 * Utils for casting number types to other number types 005 */ 006 public final class NumberConversions { 007 private NumberConversions() {} 008 009 public static int floor(double num) { 010 final int floor = (int) num; 011 return floor == num ? floor : floor - (int) (Double.doubleToRawLongBits(num) >>> 63); 012 } 013 014 public static int ceil(final double num) { 015 final int floor = (int) num; 016 return floor == num ? floor : floor + (int) (~Double.doubleToRawLongBits(num) >>> 63); 017 } 018 019 public static int round(double num) { 020 return floor(num + 0.5d); 021 } 022 023 public static double square(double num) { 024 return num * num; 025 } 026 027 public static int toInt(Object object) { 028 if (object instanceof Number) { 029 return ((Number) object).intValue(); 030 } 031 032 try { 033 return Integer.valueOf(object.toString()); 034 } catch (NumberFormatException e) { 035 } catch (NullPointerException e) { 036 } 037 return 0; 038 } 039 040 public static float toFloat(Object object) { 041 if (object instanceof Number) { 042 return ((Number) object).floatValue(); 043 } 044 045 try { 046 return Float.valueOf(object.toString()); 047 } catch (NumberFormatException e) { 048 } catch (NullPointerException e) { 049 } 050 return 0; 051 } 052 053 public static double toDouble(Object object) { 054 if (object instanceof Number) { 055 return ((Number) object).doubleValue(); 056 } 057 058 try { 059 return Double.valueOf(object.toString()); 060 } catch (NumberFormatException e) { 061 } catch (NullPointerException e) { 062 } 063 return 0; 064 } 065 066 public static long toLong(Object object) { 067 if (object instanceof Number) { 068 return ((Number) object).longValue(); 069 } 070 071 try { 072 return Long.valueOf(object.toString()); 073 } catch (NumberFormatException e) { 074 } catch (NullPointerException e) { 075 } 076 return 0; 077 } 078 079 public static short toShort(Object object) { 080 if (object instanceof Number) { 081 return ((Number) object).shortValue(); 082 } 083 084 try { 085 return Short.valueOf(object.toString()); 086 } catch (NumberFormatException e) { 087 } catch (NullPointerException e) { 088 } 089 return 0; 090 } 091 092 public static byte toByte(Object object) { 093 if (object instanceof Number) { 094 return ((Number) object).byteValue(); 095 } 096 097 try { 098 return Byte.valueOf(object.toString()); 099 } catch (NumberFormatException e) { 100 } catch (NullPointerException e) { 101 } 102 return 0; 103 } 104 }