这是一个网上书店程序中的两个JavaBean
[BookBean.java存储数据库中图书的信息]
[code="java"]
package org.sunxin.ch09.bookstore;
import java.io.Serializable;
public class BookBean implements Serializable {
private int id;
private String title;
private float price;
private int amount;
public BookBean() {
}
public BookBean(int id, String title, float price, int amount) {
this.id = id;
this.title = title;
this.price = price;
this.amount = amount;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
}
[/code]
[CartItemBean.java表示用户放到购物车中的一项条目,条目中包含的内容有表示图书信息的Bookbean对象,购买图书的数量和本项条目的合计价格]
[code="java"]
package org.sunxin.ch09.bookstore;
import java.io.Serializable;
public class CartItemBean implements Serializable {
private BookBean book;
private int quantity;
public CartItemBean() {
}
public CartItemBean(BookBean book) {
this.book = book;
this.quantity = 1;
}
public BookBean getBook() {
return book;
}
public void setBook(BookBean book) {
this.book = book;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public float getItemPrice() {
float price = book.getPrice()*quantity;
long val = Math.round(price*100); //A
return val/100.0f; //B
}
}
[/code]
[size=large]请问getItemPrice()方法为什么不直接写成这样:return book.getPrice()*quantity;
A处和B处的代码是来干什么用的?不用它会有什么样的后果? [/size][color=red][/color]
[b]问题补充:[/b]
浮点数的计算不精确
不懂呀,请将详细些吧。
为什么直接计算会不精确?
为什么要用Math.round()?
[b]问题补充:[/b]
价格不都是只有两位小数的么?
....按快了
long val = Math.round(book.getPrice()*100);
return val*quantity/ 100.0f
浮点数的计算不精确
float price = book.getPrice()*quantity;
long val = Math.round(price*100); //A
return val/100.0f; //B
==》 不过我可能会这样写
long val = Math.round(book.getPrice()*100);
return val/ 100.0f
这个,你最好查下 google, 计算机在处理浮点数时,是不准确的,就像
+0.0f == -0.0f 可能会报错
所以一般在比较浮点数时,会有个最小限值,当两者之差小于某个小数时,就认为相等了,而且 math.round,则取比较接近的值吧
Math.round(price*100);这个是四舍五入的做法,觉得后面的小数太多了,然后只保留两位这样做
明显这样写: float price = book.getPrice()*quantity;
long val = Math.round(price*100); //A
return val/100.0f; //B
A和B与第一行没有了任何关系,这是勘误
举个例子给你看啊
float price = book.getPrice()*quantity;//假如price=55.286,一般除法很容易得到3位以上的值,这个你能理解吧
long val = Math.round(price*100);//price*100=5528.6这样一算就是5529
return val/100.0f;// 5529/100.0f=55.29
明白什么意思了吧