List of usage examples for java.lang Float Float
@Deprecated(since = "9") public Float(String s) throws NumberFormatException
From source file:com.examples.with.different.packagename.testcarver.NumberConverter.java
/** * Convert any Number object to the specified type for this * <i>Converter</i>./* w ww .ja v a 2 s . c o m*/ * <p> * This method handles conversion to the following types: * <ul> * <li><code>java.lang.Byte</code></li> * <li><code>java.lang.Short</code></li> * <li><code>java.lang.Integer</code></li> * <li><code>java.lang.Long</code></li> * <li><code>java.lang.Float</code></li> * <li><code>java.lang.Double</code></li> * <li><code>java.math.BigDecimal</code></li> * <li><code>java.math.BigInteger</code></li> * </ul> * @param sourceType The type being converted from * @param targetType The Number type to convert to * @param value The Number to convert. * * @return The converted value. */ private Number toNumber(Class sourceType, Class targetType, Number value) { // Correct Number type already if (targetType.equals(value.getClass())) { return value; } // Byte if (targetType.equals(Byte.class)) { long longValue = value.longValue(); if (longValue > Byte.MAX_VALUE) { throw new ConversionException( toString(sourceType) + " value '" + value + "' is too large for " + toString(targetType)); } if (longValue < Byte.MIN_VALUE) { throw new ConversionException( toString(sourceType) + " value '" + value + "' is too small " + toString(targetType)); } return new Byte(value.byteValue()); } // Short if (targetType.equals(Short.class)) { long longValue = value.longValue(); if (longValue > Short.MAX_VALUE) { throw new ConversionException( toString(sourceType) + " value '" + value + "' is too large for " + toString(targetType)); } if (longValue < Short.MIN_VALUE) { throw new ConversionException( toString(sourceType) + " value '" + value + "' is too small " + toString(targetType)); } return new Short(value.shortValue()); } // Integer if (targetType.equals(Integer.class)) { long longValue = value.longValue(); if (longValue > Integer.MAX_VALUE) { throw new ConversionException( toString(sourceType) + " value '" + value + "' is too large for " + toString(targetType)); } if (longValue < Integer.MIN_VALUE) { throw new ConversionException( toString(sourceType) + " value '" + value + "' is too small " + toString(targetType)); } return new Integer(value.intValue()); } // Long if (targetType.equals(Long.class)) { return new Long(value.longValue()); } // Float if (targetType.equals(Float.class)) { if (value.doubleValue() > Float.MAX_VALUE) { throw new ConversionException( toString(sourceType) + " value '" + value + "' is too large for " + toString(targetType)); } return new Float(value.floatValue()); } // Double if (targetType.equals(Double.class)) { return new Double(value.doubleValue()); } // BigDecimal if (targetType.equals(BigDecimal.class)) { if (value instanceof Float || value instanceof Double) { return new BigDecimal(value.toString()); } else if (value instanceof BigInteger) { return new BigDecimal((BigInteger) value); } else { return BigDecimal.valueOf(value.longValue()); } } // BigInteger if (targetType.equals(BigInteger.class)) { if (value instanceof BigDecimal) { return ((BigDecimal) value).toBigInteger(); } else { return BigInteger.valueOf(value.longValue()); } } String msg = toString(getClass()) + " cannot handle conversion to '" + toString(targetType) + "'"; throw new ConversionException(msg); }
From source file:com.fengduo.bee.commons.core.lang.CollectionUtils.java
public static List<Float> getFloatValues(Collection<?> values, String property) { return getProperty(values, property, new Float(0f)); }
From source file:com.salesmanager.core.module.impl.application.prices.MonthlyPriceModule.java
public String getHtmlPriceFormated(String prefix, ProductPrice productPrice, Locale locale, String currency) { if (locale == null) locale = LocaleUtil.getDefaultLocale(); if (currency == null) currency = CurrencyUtil.getDefaultCurrency(); StringBuffer p = new StringBuffer(); p.append("<div class='product-price product-monthly-price'>"); if (!ProductUtil.hasDiscount(productPrice)) { p.append("<div style='width:50%;float:left;'>"); if (!StringUtils.isBlank(prefix)) { p.append("<div class='product-price-text'><strong>").append(prefix).append(" : </strong></div>"); }//from w w w. ja va 2s .c om p.append( CurrencyUtil.displayFormatedAmountWithCurrency(productPrice.getProductPriceAmount(), currency)); p.append(getPriceSuffixText(currency, locale)); p.append("</div>"); p.append("<div class='product-line'> </div>"); } else { double arith = productPrice.getSpecial().getProductPriceSpecialAmount().doubleValue() / productPrice.getProductPriceAmount().doubleValue(); double fsdiscount = 100 - arith * 100; Float percentagediscount = new Float(fsdiscount); String savediscount = String.valueOf(percentagediscount.intValue()); p.append("<div class='product-price product-monthly-price'>"); if (!StringUtils.isBlank(prefix)) { p.append("<div class='product-price-text'><strong>").append(prefix).append(" : </strong></div>"); } p.append("<strike>") .append(CurrencyUtil.displayFormatedAmountWithCurrency(productPrice.getProductPriceAmount(), currency)) .append(getPriceSuffixText(currency, locale)).append("</strike>").append("</div>") .append("<div style='width:50%;float:right;'>").append("<font color='red'>") .append(CurrencyUtil.displayFormatedAmountWithCurrency(ProductUtil.determinePrice(productPrice), currency)) .append(getPriceSuffixText(currency, locale)).append("</font>").append("<br>") .append("<font color='red' style='font-size:75%;'>") .append(LabelUtil.getInstance().getText(locale, "label.generic.save")).append(" :") .append(savediscount) .append(LabelUtil.getInstance().getText(locale, "label.generic.percentsign")).append(" ") .append(LabelUtil.getInstance().getText(locale, "label.generic.off")).append("</font>"); Date discountEndDate = ProductUtil.getDiscountEndDate(productPrice); if (discountEndDate != null) { p.append("<br>").append(" <font style='font-size:65%;'>") .append(LabelUtil.getInstance().getText(locale, "label.generic.until")).append(" ") .append(DateUtil.formatDate(discountEndDate)).append("</font>"); } p.append("</div>"); } p.append("</div>"); return p.toString(); }
From source file:mp.teardrop.Song.java
static Song fromJsonObject(JSONObject jsonBourne) { try {//from w w w .j av a2 s. co m Song song = new Song(jsonBourne.getBoolean("isCloudSong"), jsonBourne.getString("path"), jsonBourne.getString("title"), jsonBourne.getString("album"), jsonBourne.getString("artist"), jsonBourne.getInt("trackNumber")); if (song.isCloudSong) { song.id = -1337; song.albumId = -1337; song.artistId = -1337; song.dbPath = jsonBourne.getString("dbPath"); song.rgTrack = //TODO: make sure there isn't any loss of precision jsonBourne.has("rgTrack") ? new Float(jsonBourne.getDouble("rgTrack")) : null; song.rgAlbum = jsonBourne.has("rgAlbum") ? new Float(jsonBourne.getDouble("rgAlbum")) : null; } else { song.id = jsonBourne.getLong("id"); song.artistId = jsonBourne.getLong("artistId"); song.albumId = jsonBourne.getLong("albumId"); song.dbPath = null; } return song; } catch (JSONException e) { return null; } }
From source file:chat.client.agent.ChatClientAgent.java
public static float distance(float lat1, float lng1, float lat2, float lng2) { double earthRadius = 3958.75; double dLat = Math.toRadians(lat2 - lat1); double dLng = Math.toRadians(lng2 - lng1); double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * Math.sin(dLng / 2) * Math.sin(dLng / 2); double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); double dist = earthRadius * c; int meterConversion = 1609; return new Float(dist * meterConversion).floatValue(); }
From source file:gov.nih.nci.ncicb.tcga.dcc.datareports.service.ProjectCaseDashboardServiceImpl.java
/** * getQCPassRate//from w w w.j av a 2s .c om * * @param jsonPassRate * @param shipped * @param pending * @param total * @return double value */ protected float getQCPassRate(float jsonPassRate, int shipped, int pending, int total) { if ((shipped + pending) < 100) { return .5f; } else { if (jsonPassRate > 0f) { return jsonPassRate; } float passRate = .5f; if (total != 0) { passRate = (new Float(shipped) + new Float(pending)) / new Float(total); } return passRate == 0f ? .5f : passRate; } }
From source file:com.linkedin.pinot.segments.v1.creator.DictionariesTest.java
@Test public void testLongColumnPreIndexStatsCollector() throws Exception { FieldSpec spec = new DimensionFieldSpec("column1", DataType.LONG, true); AbstractColumnStatisticsCollector statsCollector = new LongColumnPreIndexStatsCollector(spec); statsCollector.collect(new Integer(1)); Assert.assertTrue(statsCollector.isSorted()); statsCollector.collect(new Float(2)); Assert.assertTrue(statsCollector.isSorted()); statsCollector.collect(new Long(3)); Assert.assertTrue(statsCollector.isSorted()); statsCollector.collect(new Double(4)); Assert.assertTrue(statsCollector.isSorted()); statsCollector.collect(new Integer(4)); Assert.assertTrue(statsCollector.isSorted()); statsCollector.collect(new Float(2)); Assert.assertFalse(statsCollector.isSorted()); statsCollector.collect(new Double(40)); Assert.assertFalse(statsCollector.isSorted()); statsCollector.collect(new Double(20)); Assert.assertFalse(statsCollector.isSorted()); statsCollector.seal();/*from www .ja va2 s .c o m*/ Assert.assertEquals(statsCollector.getCardinality(), 6); Assert.assertEquals(((Number) statsCollector.getMinValue()).intValue(), 1); Assert.assertEquals(((Number) statsCollector.getMaxValue()).intValue(), 40); Assert.assertFalse(statsCollector.isSorted()); }
From source file:com.timtripcony.AbstractSmartDocumentModel.java
/** * Converts a field value to a currency string * //from w ww .j a v a 2 s . co m * @param value * Object value to convert * @param forceDecimals * boolean whether or the currency value should force decimals even if a whole number * @return String value as a currency */ public String convertToCurrency(Object value, boolean forceDecimals) { String retVal_ = ""; try { if (value instanceof Number) { float number = new Float(value.toString()); float epsilon = 0.004f; // 4 tenths of a penny if (!forceDecimals && Math.abs(Math.round(number) - number) < epsilon) { retVal_ = String.format("%10.0f", number); // sdb } else { retVal_ = String.format("%10.2f", number); // dj_segfault } } } catch (Throwable t) { AppUtils.handleException(t); } return StringUtils.trim(retVal_); }
From source file:edu.lternet.pasta.dml.database.DatabaseAdapter.java
/** * Creates a SQL command to insert data. If some error happens, null will be * returned.// w w w .j a v a 2 s .c o m * * @param attributeList AttributeList which will be inserted * @param tableName The name of the table which the data will be inserted into * @param oneRowData The data vector which contains data to be inserted * @return A SQL String that can be run to insert one row of data into table */ public String generateInsertSQL(AttributeList attributeList, String tableName, Vector oneRowData) throws DataNotMatchingMetadataException, SQLException { String sqlString = null; int NULLValueCounter = 0; int hasValueCounter = 0; if (attributeList == null) { throw new SQLException("The attribute list is null and couldn't generate insert sql statement"); } if (oneRowData == null || oneRowData.isEmpty()) { throw new SQLException("The the data is null and couldn't generte insert sql statement"); } StringBuffer sqlAttributePart = new StringBuffer(); StringBuffer sqlDataPart = new StringBuffer(); sqlAttributePart.append(INSERT); sqlAttributePart.append(SPACE); sqlAttributePart.append(tableName); sqlAttributePart.append(LEFTPARENTH); sqlDataPart.append(SPACE); sqlDataPart.append(VALUES); sqlDataPart.append(SPACE); sqlDataPart.append(LEFTPARENTH); Attribute[] list = attributeList.getAttributes(); if (list == null || list.length == 0) { throw new SQLException("The attributes is null and couldn't generate insert sql statement"); } int size = list.length; // column name part boolean firstAttribute = true; for (int i = 0; i < size; i++) { // if data vector Object obj = oneRowData.elementAt(i); String value = null; if (obj == null) { NULLValueCounter++; continue; } else { value = (String) obj; if (value.trim().equals("")) { continue; } } Attribute attribute = list[i]; if (attribute == null) { throw new SQLException("Attribute list contains a null attribute"); } String[] missingValues = attribute.getMissingValueCode(); boolean isMissingValue = isMissingValue(value, missingValues); if (isMissingValue) { continue; } String name = attribute.getDBFieldName(); String attributeType = getAttributeType(attribute); if (!firstAttribute) { sqlAttributePart.append(COMMA); sqlDataPart.append(COMMA); } sqlAttributePart.append(name); Domain domain = attribute.getDomain(); /* If attributeType is "datetime", convert to a timestamp * and wrap single quotes around the value. But only if we * have a format string! */ if (attributeType.equalsIgnoreCase("datetime")) { String formatString = ((DateTimeDomain) domain).getFormatString(); // Transform the datetime format string for database compatibility formatString = transformFormatString(formatString); // Transform the datetime value for database compatibility value = transformDatetime(value); value = escapeSpecialCharacterInData(value); sqlDataPart.append(TO_DATE_FUNCTION); sqlDataPart.append(LEFTPARENTH); sqlDataPart.append(SINGLEQUOTE); sqlDataPart.append(value); sqlDataPart.append(SINGLEQUOTE); sqlDataPart.append(COMMA); sqlDataPart.append(SINGLEQUOTE); sqlDataPart.append(formatString); sqlDataPart.append(SINGLEQUOTE); sqlDataPart.append(RIGHTPARENTH); hasValueCounter++; log.debug("datetime value expression= " + sqlDataPart.toString()); } /* If domain is null or it is not NumericDomain we assign it text type * and wrap single quotes around the value. */ else if (attributeType.equals("string")) { value = escapeSpecialCharacterInData(value); sqlDataPart.append(SINGLEQUOTE); sqlDataPart.append(value); sqlDataPart.append(SINGLEQUOTE); hasValueCounter++; } /* Else we have a NumericDomain. Determine whether it is a float or * integer. */ else { String dataType = mapDataType(attributeType); try { if (dataType.equals("FLOAT")) { Float floatObj = new Float(value); float floatNum = floatObj.floatValue(); sqlDataPart.append(floatNum); } else { Integer integerObj = new Integer(value); int integerNum = integerObj.intValue(); sqlDataPart.append(integerNum); } } catch (Exception e) { log.error("Error determining numeric value: " + e.getMessage()); throw new DataNotMatchingMetadataException( "Data value '" + value + "' is NOT the expected data type of '" + dataType + "'"); } hasValueCounter++; } firstAttribute = false; } // If all data is null, return null value for sql string. if (NULLValueCounter == list.length || hasValueCounter == 0) { return sqlString; } sqlAttributePart.append(RIGHTPARENTH); sqlDataPart.append(RIGHTPARENTH); sqlDataPart.append(SEMICOLON); // Combine the two parts sqlAttributePart.append(sqlDataPart.toString()); sqlString = sqlAttributePart.toString(); return sqlString; }
From source file:com.availo.wms.plugin.vhostloadbalancer.LoadBalancerRedirectorBandwidth.java
public List<Map<String, Object>> getInfo(String vhostName) { List<Map<String, Object>> ret = new ArrayList<Map<String, Object>>(); synchronized (lock) { // Iterator<ServerHolder> iter = serverMap.values().iterator(); /*//from w ww. j a v a 2 s . c o m * Hopefully, this change doesn't break anything. This was done to make it easier to debug the full output in ServerInfo*, * by using a sorted set of servers instead of the default. * * Should be safe, I guess, since "servers", as opposed to "serverMap", is used by getRedirect(). */ Iterator<ServerHolder> iter = servers.iterator(); // Iterate through all the "LoadBalancerSender"-servers that are currently active while (iter.hasNext()) { ServerHolder serverHolder = iter.next(); Map<String, Object> map = new HashMap<String, Object>(); map.put("serverId", serverHolder.serverId); map.put("status", LoadBalancerUtils.statusToString(serverHolder.status)); String redirectAddress = null; // This means that the getInfo-request came through an IP address that we know belongs to a VHost on the LoadBalancerListener. Ignore all other vhosts. if (vhostName != null) { if (serverHolder != null && serverHolder.vhosts != null) { if (serverHolder.vhosts.containsKey(vhostName)) { Map<String, Object> vhostProperties = (Map<String, Object>) serverHolder.vhosts .get(vhostName); // We found a redirect address for this VHost, and everything works as intended. Remember this VHost's redirect address, so we can add it later on if (vhostProperties.containsKey("redirectAddress") && vhostProperties.get("redirectAddress") != null) { redirectAddress = (String) vhostProperties.get("redirectAddress"); } // No redirect address for this VHost, but we have other properties. Log this as an error. else { // !vhostProperties.containsKey("redirectAddress") // This is probably either one or more servers with a configuration error, or a redirect request through a VHost that isn't intended to be used for load balancing WMSLoggerFactory.getLogger(LoadBalancerRedirectorBandwidth.class).warn( "LoadBalancerRedirectorConcurrentConnects.getInfo: Got a redirect request from vhost '" + vhostName + "', but we couldn't find any redirect address for this vhost. Check the relevant VHost.xml config on '" + serverHolder.redirect + "'"); } } // The requested VHost doesn't exist in the LoadBalancer config for this server. else { // !serverHolder.vhosts.containsKey(vhostName) // Same as above, this is probably either one or more servers with a configuration error, or a redirect request through a VHost that isn't intended to be used for load balancing WMSLoggerFactory.getLogger(LoadBalancerRedirectorBandwidth.class).warn( "LoadBalancerRedirectorConcurrentConnects.getInfo: Got a redirect request from vhost '" + vhostName + "', but we couldn't find any properties for this vhost on the server '" + serverHolder.redirect + "'"); } } else { // serverHolder == null || serverHolder.vhosts == null // This means that *no* vhosts are known at all for this particular server (serverHolder). // Likely cause for this is one or more servers with a "stock" LoadBalancer, i.e. not running VHostloadBalancer WMSLoggerFactory.getLogger(LoadBalancerRedirectorBandwidth.class).warn( "LoadBalancerRedirectorConcurrentConnects.getInfo: Got a redirect request from vhost '" + vhostName + "', but we have a server with no VHost data. Check the modules and configs on '" + serverHolder.redirect + "'"); } } if (redirectAddress != null) { // This means that we found a redirect address for this particular VHost, so let's use it map.put("redirect", redirectAddress); } else { // This will use the default redirectAddress from Server.xml, for legacy servers. Possibly not a good idea in all use-cases. //WMSLoggerFactory.getLogger(LoadBalancerRedirectorBandwidth.class).info("LoadBalancerRedirectorConcurrentConnects.getInfo: Adding default redirect address '" + serverHolder.redirect + "' to the server list for VHost '" + vhostName + "'."); map.put("redirect", serverHolder.redirect); } /* * Uncomment the following three lines if you want to output information about all available vhosts. * It doesn't make any sense from a practical point of view, but could be helpful while debugging. * Note: The LoadBalancerUtils is closed source, so LoadBalancerUtils.serverInfoToXMLStr() is not VHosts-aware, and * will just output the information in a single XML tag. The JSON output works better in this regard. */ /*if (serverHolder.vhosts != null && serverHolder.vhosts.size() > 0) { map.put("VHosts", serverHolder.vhosts); }*/ map.put("weight", new Integer(serverHolder.weight)); map.put("inRate", new Integer(serverHolder.inRate)); map.put("outRate", new Integer(serverHolder.outRate)); map.put("connectCount", new Integer(serverHolder.connectCount)); map.put("redirectCount", new Integer(serverHolder.redirectCount)); map.put("debug", new Float(serverHolder.outRate / serverHolder.weight)); while (true) { if (this.listener == null) { break; } LoadBalancerServer loadBalancerServer = this.listener.getServer(serverHolder.serverId); if (loadBalancerServer == null) { break; } map.put("lastMessage", loadBalancerServer.getLastMessageReceiveTimeStr()); break; } ret.add(map); } } return ret; }