将小数位数限制为两个位置的简单方法

时间:2017-03-07 18:47:44

标签: java double decimal

    public static void main(String[] args) {//begin main
    Scanner worksheet = new Scanner(System.in);
       {
        double radi;
        double area;
        double circum;
        double pie = 3.14;

        System.out.println("Enter the radius: ");
        radi = worksheet.nextDouble();//enter 1.2 

        area = pie * radi * radi;

区域为4.521599999999999,但我希望它为4.52。

        System.out.println("The area is:" + area);

        circum=2*pie*radi;

circum出现在7.536。 希望它是7.53

        System.out.println("The circumference is:"+circum);

    }

如何在没有方法的情况下将值截断为2位小数。

1 个答案:

答案 0 :(得分:0)

你可以尝试

int temp = (int)(circum*100);//452
circum = temp/100d;//4.52

或者您可以简单地执行此操作

@Singleton  
@Startup  
public class CassandraDAO<T extends Serializable> extends AbstractDAO {  

  private EntityManagerFactory emf;  
  // @PersistenceContext(unitName = "JPAService")  
  private EntityManager em;  

  @PostConstruct  
  public void init() {  
    System.out.println("***************** init CassandraDAO ***************************");  
    emf = Persistence.createEntityManagerFactory("JPAService");  
    em = emf.createEntityManager();  
  }  

  @PreDestroy  
  public void destroy() {  
    System.out.println("***************** destroying CassandraDAO *************************");  
    if (em.isOpen()) {  
      em.close();  
    }  
    if (emf.isOpen()) {  
      emf.close();  
    }  
  }  

  @Override  
  public EntityManager getManager() {  
    return em;  
  }  

  @Override  
  public void setManager(EntityManager em) {  
    this.em = em;  
  }  

  @Override  
  public EntityManagerFactory getEntityManagerFactory() {  
    return emf;  
  }  

  @Override  
  public void setEntityManagerFactory(EntityManagerFactory emf) {  
    this.emf = emf;  
  }  
}  

这两个都会将值限制为最多2个小数点。

希望它能解决问题。

Reference (Take a look at this)