Java中字符串相乘
我有一个包含数字的字符串,我想将该数字与 1.28 相乘,
这是字符串的分配方式
String PRICE = dataRecord.get( "PRICE" );
I have a String which contains a number and I would like to multiply that number with 1.28
Here is how the string is assigned
String PRICE = dataRecord.get( "PRICE" );
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您需要获取数据的数字表示形式并对其执行乘法。由于示例是“价格”,我假设涉及金钱,因此建议使用小数类型。
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.
更好的方法是使用具有双字段类型的适当对象。
类似于 @Rob 的示例,它给出了相同的答案。您决定哪个更简单。 ;)
为了金钱,我建议使用 double 并进行适当的舍入。
A better way would be to use a proper object with a double field type.
Similar to @Rob's example which gives the same answer. You decide which is simpler. ;)
For money, I recommend using double with appropriate rounding.
您真正想要的是:
假设 dataRecord 是 ResultSet 对象。无论如何,使用 BigDecimals 会好得多,并且,如果 PRICE 确实存储在 String 对象中,那么我假设您这样做是因为您知道浮点精度问题。
What you really want, is:
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.
将字符串转换为双精度型以进行乘法。 Double.parseDouble() 是您可以使用的方法。我选择将其包装在 try 块中,以防字符串格式错误并引发错误(如果价格由于某种原因不是数字 - 例如 5.67b 或 8..34)。
作为您的参考,这里是 parseDouble() 的文档。
<我>
公共静态双 parseDouble(String s)
抛出 NumberFormatException
返回一个新的 double,初始化为指定 String 表示的值,由 Double 类的 valueOf 方法执行。
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).
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.
浮点数学。使用 BigDecimal 并且您需要设置结果的比例以调用舍入,因为比例很可能会比您想要的更大。
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.
简单的方法:执行以下操作
Double.ParseInt("Stringname"),将 reutnr 双精度值
如果您喜欢这个答案,请给予一些信任
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
If you don't need to convert it to a String after multiplying the value just remove the last line.