List of usage examples for java.lang Number toString
public String toString()
From source file:org.opentaps.common.util.UtilCommon.java
/** * Converts a localized number <code>String</code> to a <code>BigDecimal</code> using the given <code>Locale</code>, defaulting to the system <code>Locale</code>. * @param locale the <code>Locale</code> to use for parsing the number, optional, defaults to the system <code>Locale</code> * @param numberString a <code>String</code> to convert to a <code>BigDecimal</code> * @return the corresponding <code>BigDecimal</code> value * @throws ParseException if an occurs during parsing *//*from w ww. j a va2s . c o m*/ public static BigDecimal parseLocalizedNumber(Locale locale, String numberString) throws ParseException { locale = UtilMisc.ensureLocale(locale); NumberFormat parser = NumberFormat.getNumberInstance(locale); Number n = parser.parse(numberString); return new BigDecimal(n.toString()); }
From source file:org.kuali.rice.core.web.format.CurrencyFormatter.java
/** * Returns a string representation of its argument formatted as a currency value. * * begin Kuali Foundation modification//from w w w. j a va 2s. c o m * @see org.kuali.rice.core.web.format.Formatter#format(java.lang.Object) * end Kuali Foundation modification */ // begin Kuali Foundation modification @Override // end Kuali Foundation modification public Object format(Object obj) { // begin Kuali Foundation modification // major code rewrite, original code commented /* if (obj == null) return null; NumberFormat formatter = NumberFormat.getCurrencyInstance(); String string = null; try { BigDecimal number = (BigDecimal) obj; number = number.setScale(SCALE, BigDecimal.ROUND_HALF_UP); string = formatter.format(number.doubleValue()); } catch (IllegalArgumentException e) { throw new FormatException(FORMAT_MSG + obj, e); } catch (ClassCastException e) { throw new FormatException(FORMAT_MSG + obj, e); } return showSymbol() ? string : removeSymbol(string); */ LOG.debug("format '" + obj + "'"); if (obj == null) { return null; } if (obj instanceof String && StringUtils.isEmpty((String) obj)) { return null; } NumberFormat formatter = getCurrencyInstanceUsingParseBigDecimal(); String string = null; try { Number number; if (obj instanceof KualiInteger) { formatter.setMaximumFractionDigits(0); number = (KualiInteger) obj; // Note that treating the number as a KualiDecimal below is obsolete. But it doesn't do any harm either since // we already set maximumFractionDigits above. } else { number = (KualiDecimal) obj; } // run the incoming KualiDecimal's string representation through convertToObject, so that KualiDecimal objects // containing ill-formatted incoming values will cause the same errors here that ill-formatted Strings do in // convertToObject KualiDecimal convertedNumber = (KualiDecimal) convertToObject(number.toString()); string = formatter.format(convertedNumber.bigDecimalValue()); } catch (IllegalArgumentException e) { throw new FormatException("formatting", RiceKeyConstants.ERROR_CURRENCY, obj.toString(), e); } catch (ClassCastException e) { throw new FormatException("formatting", RiceKeyConstants.ERROR_CURRENCY, obj.toString(), e); } return showSymbol() ? string : removeSymbol(string); // end Kuali Foundation modification }
From source file:NumberUtils.java
/** * Convert the given number into an instance of the given target class. * @param number the number to convert/*from w w w. jav a 2 s . c o m*/ * @param targetClass the target class to convert to * @return the converted number * @throws IllegalArgumentException if the target class is not supported * (i.e. not a standard Number subclass as included in the JDK) * @see java.lang.Byte * @see java.lang.Short * @see java.lang.Integer * @see java.lang.Long * @see java.math.BigInteger * @see java.lang.Float * @see java.lang.Double * @see java.math.BigDecimal */ public static Number convertNumberToTargetClass(Number number, Class<?> targetClass) throws IllegalArgumentException { // Assert.notNull(number, "Number must not be null"); // Assert.notNull(targetClass, "Target class must not be null"); if (targetClass.isInstance(number)) { return number; } else if (targetClass.equals(Byte.class)) { long value = number.longValue(); if (value < Byte.MIN_VALUE || value > Byte.MAX_VALUE) { raiseOverflowException(number, targetClass); } return new Byte(number.byteValue()); } else if (targetClass.equals(Short.class)) { long value = number.longValue(); if (value < Short.MIN_VALUE || value > Short.MAX_VALUE) { raiseOverflowException(number, targetClass); } return new Short(number.shortValue()); } else if (targetClass.equals(Integer.class)) { long value = number.longValue(); if (value < Integer.MIN_VALUE || value > Integer.MAX_VALUE) { raiseOverflowException(number, targetClass); } return new Integer(number.intValue()); } else if (targetClass.equals(Long.class)) { return new Long(number.longValue()); } else if (targetClass.equals(Float.class)) { return new Float(number.floatValue()); } else if (targetClass.equals(Double.class)) { return new Double(number.doubleValue()); } else if (targetClass.equals(BigInteger.class)) { return BigInteger.valueOf(number.longValue()); } else if (targetClass.equals(BigDecimal.class)) { // using BigDecimal(String) here, to avoid unpredictability of BigDecimal(double) // (see BigDecimal javadoc for details) return new BigDecimal(number.toString()); } else { throw new IllegalArgumentException("Could not convert number [" + number + "] of type [" + number.getClass().getName() + "] to unknown target class [" + targetClass.getName() + "]"); } }
From source file:com.nsano.uat.StatusServlet.java
/** * * @param request// w w w . j a v a 2s . c o m * @return * @throws IOException */ private String moneytransfer(HttpServletRequest request) throws IOException, JSONException, NoSuchAlgorithmException { // joined json string String join = ""; JsonElement root = null; JsonElement root2 = null; JsonElement root3 = null; String responseobject = ""; //String nickname="KENDYIPL"; // These represent parameters received over the network String tag = "", apikey = "", refID = "", sender = "", sender_country = "", receiver = "", receiver_msisdn = "", receiver_country = "", amount = "", mno = ""; //referenceid, customermsisdn, nickname,amount, batchref, username, password, narrative // Get all parameters, the keys of the parameters are specified List<String> lines = IOUtils.readLines(request.getReader()); // used to format/join incoming JSon string join = StringUtils.join(lines.toArray(), ""); //############################################################################### // instantiate the JSon //Note //The = sign is encoded to \u003d. Hence you need to use disableHtmlEscaping(). //############################################################################### Gson g = new GsonBuilder().disableHtmlEscaping().create(); //Gson g = new Gson(); Map<String, String> expected = new HashMap<>(); try { // parse the JSon string //referenceid, customermsisdn, nickname,amount, batchref, username, password, narrative root = new JsonParser().parse(join); tag = root.getAsJsonObject().get("tag").getAsString(); apikey = root.getAsJsonObject().get("apikey").getAsString(); refID = root.getAsJsonObject().get("refID").getAsString(); sender = root.getAsJsonObject().get("sender").getAsString(); sender_country = root.getAsJsonObject().get("sender_country").getAsString(); receiver = root.getAsJsonObject().get("receiver").getAsString(); receiver_msisdn = root.getAsJsonObject().get("receiver_msisdn").getAsString(); receiver_country = root.getAsJsonObject().get("receiver_country").getAsString(); amount = root.getAsJsonObject().get("amount").getAsString(); mno = root.getAsJsonObject().get("mno").getAsString(); } catch (Exception e) { expected.put("command_status", "COMMANDSTATUS_INVALID_PARAMETERS"); String jsonResult = g.toJson(expected); System.out.println(e); return jsonResult; } //check for the presence of all required parameters if (StringUtils.isBlank(tag) || StringUtils.isBlank(apikey) || StringUtils.isBlank(refID) || StringUtils.isBlank(sender) || StringUtils.isBlank(sender_country) || StringUtils.isBlank(receiver) || StringUtils.isBlank(receiver_msisdn) || StringUtils.isBlank(receiver_country) || StringUtils.isBlank(amount) || StringUtils.isBlank(mno)) { //expected.put("username", username); expected.put("status_code", statuscode); expected.put("status_description", Statusdescription); String jsonResult = g.toJson(expected); return jsonResult; } //assign the remit url from properties.config //String processtransaction = airtelbalance.AirtelBalance( nickname, username, password); String processtransaction = st.sendPOST(); //capture the switch respoinse. System.out.println(processtransaction); //pass the returned json string JsonElement roots = new JsonParser().parse(processtransaction); //JsonElement rootsone = roots.getAsJsonObject(); //exctract a specific json element from the object(status_code) //Double code = roots.getAsJsonObject().get("code").getAsDouble(); Number code = roots.getAsJsonObject().get("code").getAsNumber(); System.out.println("####################################################################"); System.out.println(code); System.out.println("####################################################################"); String msg = roots.getAsJsonObject().get("msg").getAsString(); System.out.println(msg); System.out.println("#####################################################################"); //String d ata = rootsone.getAsJsonObject().get("error_type").getAsString(); // loop array //add //expected.put("username", username); expected.put("code", code.toString()); expected.put("msg", msg.toString()); //expected.put("error_type", data.toString()); String jsonResult = g.toJson(expected); if (code.toString() == "01") { System.out.println("fail"); } else { System.out.println("success"); } return jsonResult; }
From source file:de.zib.scalaris.examples.wikipedia.bliki.MyWikiModel.java
/** * Formats the given number using the wiki's locale. * //from w w w . j av a 2s . co m * Note: Currently, the English locale is always used. * * @param rawNumber * whether the raw number should be returned * @param number * the number * * @return the formatted number */ public String formatStatisticNumber(boolean rawNumber, Number number) { if (rawNumber) { return number.toString(); } else { // TODO: use locale from Wiki NumberFormat nf = NumberFormat.getNumberInstance(Locale.ENGLISH); nf.setGroupingUsed(true); return nf.format(number); } }
From source file:org.apache.sqoop.mapreduce.hcat.SqoopHCatExportHelper.java
private Object convertNumberTypes(Object val, String javaColType) { Number n = (Number) val; if (javaColType.equals(BYTE_TYPE)) { return n.byteValue(); } else if (javaColType.equals(SHORT_TYPE)) { return n.shortValue(); } else if (javaColType.equals(INTEGER_TYPE)) { return n.intValue(); } else if (javaColType.equals(LONG_TYPE)) { return n.longValue(); } else if (javaColType.equals(FLOAT_TYPE)) { return n.floatValue(); } else if (javaColType.equals(DOUBLE_TYPE)) { return n.doubleValue(); } else if (javaColType.equals(BIG_DECIMAL_TYPE)) { return new BigDecimal(n.doubleValue()); } else if (javaColType.equals(BOOLEAN_TYPE)) { return n.byteValue() == 0 ? Boolean.FALSE : Boolean.TRUE; } else if (javaColType.equals(STRING_TYPE)) { return n.toString(); }/* w w w . j av a 2 s . c o m*/ return null; }
From source file:org.apache.velocity.tools.generic.MathTool.java
/** * This returns a random {@link Number} within the * specified range. The returned value will be * greater than or equal to the first number * and less than the second number. If both arguments * are whole numbers then the returned number will * also be, otherwise a {@link Double} will * be returned./*www . j a v a2 s. c o m*/ * * @param num1 the first number * @param num2 the second number * @return a pseudo-random {@link Number} greater than * or equal to the first number and less than * the second * @see Math#random() */ public Number random(Object num1, Object num2) { Number n1 = toNumber(num1); Number n2 = toNumber(num2); if (n1 == null || n2 == null) { return null; } double diff = n2.doubleValue() - n1.doubleValue(); // multiply the difference by a pseudo-random double from // 0.0 to 1.0, round to the nearest int, and add the first // value to the random int and return as an Integer double random = (diff * Math.random()) + n1.doubleValue(); // check if either of the args were floating points String in = n1.toString() + n2.toString(); if (in.indexOf('.') < 0) { // args were whole numbers, so return the same return matchType(n1, n2, Math.floor(random)); } // one of the args was a floating point, // so don't floor the result return new Double(random); }
From source file:org.opentaps.common.util.UtilCommon.java
/** * Converts a <code>Number</code> into a <code>BigDecimal</code>. * Note that with Java 5, you can pass in a primitive, which will be autoboxed. * @param number the <code>Number</code> to convert * @return a <code>BigDecimal</code> value, or <code>null</code> if the given number was <code>null</code> * @exception NumberFormatException if the <code>Number</code> cannot be parsed, which shouldn't happen *///from w ww . j a v a2s . c o m public static BigDecimal asBigDecimal(Number number) throws NumberFormatException { if (number == null) { return null; } if (number instanceof BigDecimal) { return (BigDecimal) number; } return new BigDecimal(number.toString()); }
From source file:org.orcid.frontend.web.controllers.FundingsController.java
/** * Transforms a string into a BigDecimal * //from www.j av a 2 s .com * @param amount * @param locale * @return a BigDecimal containing the given amount * @throws Exception * if the amount cannot be correctly parse into a BigDecimal * */ public BigDecimal getAmountAsBigDecimal(String amount, Locale locale) throws Exception { try { ParsePosition parsePosition = new ParsePosition(0); DecimalFormat numberFormat = (DecimalFormat) NumberFormat.getNumberInstance(locale); DecimalFormatSymbols symbols = numberFormat.getDecimalFormatSymbols(); /** * When spaces are allowed, the grouping separator is the character * 160, which is a non-breaking space So, lets change it so it uses * the default space as a separator * */ if (symbols.getGroupingSeparator() == 160) { symbols.setGroupingSeparator(' '); } numberFormat.setDecimalFormatSymbols(symbols); Number number = numberFormat.parse(amount, parsePosition); if (number == null || parsePosition.getIndex() != amount.length()) { throw new Exception(); } return new BigDecimal(number.toString()); } catch (Exception e) { throw e; } }
From source file:org.apache.sqoop.mapreduce.hcat.SqoopHCatImportHelper.java
private Object convertNumberTypes(Object val, HCatFieldSchema hfs) { HCatFieldSchema.Type hfsType = hfs.getType(); if (!(val instanceof Number)) { return null; }//from w w w . j av a2s . c om if (val instanceof BigDecimal && hfsType == HCatFieldSchema.Type.STRING || hfsType == HCatFieldSchema.Type.VARCHAR || hfsType == HCatFieldSchema.Type.CHAR) { BigDecimal bd = (BigDecimal) val; String bdStr = null; if (bigDecimalFormatString) { bdStr = bd.toPlainString(); } else { bdStr = bd.toString(); } if (hfsType == HCatFieldSchema.Type.VARCHAR) { VarcharTypeInfo vti = (VarcharTypeInfo) hfs.getTypeInfo(); HiveVarchar hvc = new HiveVarchar(bdStr, vti.getLength()); return hvc; } else if (hfsType == HCatFieldSchema.Type.VARCHAR) { CharTypeInfo cti = (CharTypeInfo) hfs.getTypeInfo(); HiveChar hChar = new HiveChar(bdStr, cti.getLength()); return hChar; } else { return bdStr; } } Number n = (Number) val; if (hfsType == HCatFieldSchema.Type.TINYINT) { return n.byteValue(); } else if (hfsType == HCatFieldSchema.Type.SMALLINT) { return n.shortValue(); } else if (hfsType == HCatFieldSchema.Type.INT) { return n.intValue(); } else if (hfsType == HCatFieldSchema.Type.BIGINT) { return n.longValue(); } else if (hfsType == HCatFieldSchema.Type.FLOAT) { return n.floatValue(); } else if (hfsType == HCatFieldSchema.Type.DOUBLE) { return n.doubleValue(); } else if (hfsType == HCatFieldSchema.Type.BOOLEAN) { return n.byteValue() == 0 ? Boolean.FALSE : Boolean.TRUE; } else if (hfsType == HCatFieldSchema.Type.STRING) { return n.toString(); } else if (hfsType == HCatFieldSchema.Type.VARCHAR) { VarcharTypeInfo vti = (VarcharTypeInfo) hfs.getTypeInfo(); HiveVarchar hvc = new HiveVarchar(val.toString(), vti.getLength()); return hvc; } else if (hfsType == HCatFieldSchema.Type.CHAR) { CharTypeInfo cti = (CharTypeInfo) hfs.getTypeInfo(); HiveChar hChar = new HiveChar(val.toString(), cti.getLength()); return hChar; } else if (hfsType == HCatFieldSchema.Type.DECIMAL) { BigDecimal bd = new BigDecimal(n.doubleValue(), MathContext.DECIMAL128); return HiveDecimal.create(bd); } return null; }