Here you can find the source of toTwoDigit(double f)
Parameter | Description |
---|---|
f | number to format |
public static String toTwoDigit(double f)
//package com.java2s; /*// w w w .jav a 2s . c o m * TemperatureUtils.java * * Created on March 30, 2006, 10:40 PM * * Copyright (c) 2006, Pat Farrell. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.util.Formatter; public class Main { /** * gets two digit string * @param f number to format * @return string with no more than two decimal places */ public static String toTwoDigit(double f) { if (Double.isNaN(f)) return ""; Formatter fmt = new Formatter(); if (Math.abs(Math.floor(f) - f) < .00001) { Double floor = new Double(Math.floor(f)); long asInt = floor.longValue(); return fmt.format("%d", asInt).toString(); } return fmt.format("%.2f", f).toString(); } }