Java Formatter Usage toTwoDigit(double f)

Here you can find the source of toTwoDigit(double f)

Description

gets two digit string

License

Open Source License

Parameter

Parameter Description
f number to format

Return

string with no more than two decimal places

Declaration

public static String toTwoDigit(double f) 

Method Source Code


//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();
    }
}

Related

  1. numberWithLeadingZeroes(int n, int totalChars)
  2. showVxlanHeaderOutput()
  3. substitution(Formatter formatter, int flags, int width, int precision, StringBuilder obj)
  4. toHexString(final byte[] data)
  5. toReadableSize(long bytes)
  6. toUUIDFormat(byte[] bytes)
  7. validateCondition(boolean condition, String messageFormat, Object... messageArgs)
  8. warnfErr(String format, String... params)