Multiply a string in Java
I have a String which contains a number and I would like to multiply that number with 1.28
Here i开发者_开发技巧s how the string is assigned
String PRICE = dataRecord.get( "PRICE" );
You need to obtain a numeric representation of the data and perform a multiplication on it. Since the example is "price", I'm assuming money is involved, and will therefore recommend a decimal type.
String price = "9.99";
BigDecimal priceDecimal = new BigDecimal( price );
BigDecimal total = priceDecimal.multiply( new BigDecimal( "1.28" ) );
System.out.println( total );
A better way would be to use a proper object with a double field type.
double price = dataRecord.price * 1.28;
Similar to @Rob's example which gives the same answer. You decide which is simpler. ;)
double price = 9.99;
double total = price * 1.28;
System.out.printf("%.4f%n", total);
For money, I recommend using double with appropriate rounding.
What you really want, is:
double price = dataRecord.getDouble( "PRICE" );
Assuming that dataRecord is a ResultSet object. In any way, It would be much much better to use BigDecimals, and, if PRICE is really stored in a String object, then I assume you did this because you know about the float-precision problem.
Convert the string to a double in order to do the multiplication. Double.parseDouble() is a method you could use. I chose to wrap this in a try block in case the string is malformed and an error is thrown (if price is for some reason not a number - ex. 5.67b or 8..34).
String price = dataRecord.get( "PRICE" );
try {
double p = Double.parseDouble(price);
double result = p*1.28;
System.out.println(result);
} catch(NumberFormatException e) { // ERROR HANDLING
System.out.println("Error parsing string: Price is not a number.");
}
For your reference, here is the documentation for parseDouble().
public static double parseDouble(String s) throws NumberFormatException
Returns a new double initialized to the value represented by the specified String, as performed by the valueOf method of class Double.
Floating point math. Use BigDecimal and you need to set the scale on the result to invoke rounding as most likely the scale will be bigger than what you want.
private static final BigDecimal MULT = new BigDecimal("1.28");
BigDecimal price = new BigDecimal(dataRecord.get("PRICE"));
BigDecimal result = price.multiply(MULT).setScale(2, RoundingMode.HALF_EVEN);
Simple way: do the following Double.ParseInt("Stringname"), will reutnr the double value PLS give some credit if you like the answer
I hope this is what you are looking for
String priceAsString = dataRecord.get( "PRICE" );
double priceAsInt = Double.valueOf(priceAsString).doubleValue();
double multipliedPrice = priceAsInt * 1.28;
If you don't need to convert it to a String after multiplying the value just remove the last line.
精彩评论