---
title: "float保留两位小数的方法"
author: "lectery"
date: "2010-05-05T16:19:12Z"
tags: []
categories: ["编程语言"]
slug: "float"
draft: false
lastmod: "2010-11-10T15:07:54Z"
id: 659654
url: "https://lectery.iteye.com/blog/659654"
---

有时候需要对float的小数位数进行限制，通常最简单的两种方法如下：

1. 使用DecimalFormat：
   
   ```
   float fv = 1234.56789f ;
   
   DecimalFormat df = new DecimalFormat("####.##");
   
   System.out(df.format(fv));
   ```
2. 可以先将float变量乘以100转成整数，之后再除以100：
   
   ```
   float f = 1.23456f;
   f = Math.round(f*100)/100f;
   ```