001/*
002 * Copyright (C) 2014 Jörg Prante
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.xbib.elasticsearch.plugin.jdbc.util;
017
018import java.text.NumberFormat;
019import java.util.Locale;
020
021public class VolumeFormatUtil {
022
023    public static String convertFileSize(double size) {
024        return convertFileSize(size, Locale.getDefault());
025    }
026
027    public static String convertFileSize(double size, Locale locale) {
028        String strSize;
029        long kb = 1024;
030        long mb = 1024 * kb;
031        long gb = 1024 * mb;
032        long tb = 1024 * gb;
033
034        NumberFormat formatter = NumberFormat.getNumberInstance(locale);
035        formatter.setMaximumFractionDigits(2);
036        formatter.setMinimumFractionDigits(2);
037
038        if (size < kb) {
039            strSize = size + " bytes";
040        } else if (size < mb) {
041            strSize = formatter.format(size / kb) + " KB";
042        } else if (size < gb) {
043            strSize = formatter.format(size / mb) + " MB";
044        } else if (size < tb) {
045            strSize = formatter.format(size / gb) + " GB";
046        } else {
047            strSize = formatter.format(size / tb) + " TB";
048        }
049        return strSize;
050    }
051}