64位双精度数可以精确表示整数+/- 2 53

鉴于这个事实,我选择对所有类型使用双精度类型作为单个类型,因为我最大的整数是无符号的32位。

但是现在我必须打印这些伪整数,但是问题是它们也与实际的双精度数混合在一起。

那么,如何在Java中很好地打印这些双打呢?

我尝试了String.format("%f", value) ,它很接近,除了对于小值,我会得到很多尾随零。

这是%f的示例输出

232.00000000
0.18000000000
1237875192.0
4.5800000000
0.00000000
1.23450000

我想要的是:

232
0.18
1237875192
4.58
0
1.2345

当然,我可以编写一个函数来修剪这些零,但是由于String操作,这会导致很多性能损失。 我可以使用其他格式代码做得更好吗?

编辑

Tom E.和Jeremy S.的答案都是不可接受的,因为它们都四舍五入到小数点后两位。 请在回答之前了解问题。

编辑2

请注意, String.format(format, args...)是与语言环境相关的 (请参见下面的答案)。


#1楼

我知道这是一个非常老的线程。但是我认为做到这一点的最佳方法如下:

public class Test {public static void main(String args[]){System.out.println(String.format("%s something",new Double(3.456)));System.out.println(String.format("%s something",new Double(3.456234523452)));System.out.println(String.format("%s something",new Double(3.45)));System.out.println(String.format("%s something",new Double(3)));}
}

输出:

3.456 something
3.456234523452 something
3.45 something
3.0 something

唯一的问题是没有删除.0的最后一个。 但是,如果您能够忍受这一点,那么效果最好。 %.2f会将其四舍五入到最后2个十进制数字。 因此,DecimalFormat。 如果您需要所有小数位而不是尾随零,那么这是最好的。


#2楼

String.format("%.2f", value) ;

#3楼

我制作了DoubleFormatter以将大量的双DoubleFormatter值有效地转换为漂亮的/可表示的字符串:

double horribleNumber = 3598945.141658554548844;
DoubleFormatter df = new DoubleFormatter(4,6); //4 = MaxInteger, 6 = MaxDecimal
String beautyDisplay = df.format(horribleNumber);
  • 如果V的整数部分大于MaxInteger =>以科学家格式(1.2345e + 30)显示V,否则以普通格式124.45678显示。
  • MaxDecimal决定小数位数(修剪与银行家四舍五入)

这里的代码:

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.Locale;import com.google.common.base.Preconditions;
import com.google.common.base.Strings;/*** Convert a double to a beautiful String (US-local):* * double horribleNumber = 3598945.141658554548844; * DoubleFormatter df = new DoubleFormatter(4,6);* String beautyDisplay = df.format(horribleNumber);* String beautyLabel = df.formatHtml(horribleNumber);* * Manipulate 3 instances of NumberFormat to efficiently format a great number of double values.* (avoid to create an object NumberFormat each call of format()).* * 3 instances of NumberFormat will be reused to format a value v:* * if v < EXP_DOWN, uses nfBelow* if EXP_DOWN <= v <= EXP_UP, uses nfNormal* if EXP_UP < v, uses nfAbove* * nfBelow, nfNormal and nfAbove will be generated base on the precision_ parameter.* * @author: DUONG Phu-Hiep*/
public class DoubleFormatter
{private static final double EXP_DOWN = 1.e-3;private double EXP_UP; // always = 10^maxIntegerprivate int maxInteger_;private int maxFraction_;private NumberFormat nfBelow_; private NumberFormat nfNormal_;private NumberFormat nfAbove_;private enum NumberFormatKind {Below, Normal, Above}public DoubleFormatter(int maxInteger, int maxFraction){setPrecision(maxInteger, maxFraction);}public void setPrecision(int maxInteger, int maxFraction){Preconditions.checkArgument(maxFraction>=0);Preconditions.checkArgument(maxInteger>0 && maxInteger<17);if (maxFraction == maxFraction_ && maxInteger_ == maxInteger) {return;}maxFraction_ = maxFraction;maxInteger_ = maxInteger;EXP_UP =  Math.pow(10, maxInteger);nfBelow_ = createNumberFormat(NumberFormatKind.Below);nfNormal_ = createNumberFormat(NumberFormatKind.Normal);nfAbove_ = createNumberFormat(NumberFormatKind.Above);}private NumberFormat createNumberFormat(NumberFormatKind kind) {final String sharpByPrecision = Strings.repeat("#", maxFraction_); //if you do not use Guava library, replace with createSharp(precision);NumberFormat f = NumberFormat.getInstance(Locale.US);//Apply banker's rounding:  this is the rounding mode that statistically minimizes cumulative error when applied repeatedly over a sequence of calculationsf.setRoundingMode(RoundingMode.HALF_EVEN);if (f instanceof DecimalFormat) {DecimalFormat df = (DecimalFormat) f;DecimalFormatSymbols dfs = df.getDecimalFormatSymbols();//set group separator to space instead of comma//dfs.setGroupingSeparator(' ');//set Exponent symbol to minus 'e' instead of 'E'if (kind == NumberFormatKind.Above) {dfs.setExponentSeparator("e+"); //force to display the positive sign in the exponent part} else {dfs.setExponentSeparator("e");}df.setDecimalFormatSymbols(dfs);//use exponent format if v is out side of [EXP_DOWN,EXP_UP]if (kind == NumberFormatKind.Normal) {if (maxFraction_ == 0) {df.applyPattern("#,##0");} else {df.applyPattern("#,##0."+sharpByPrecision);}} else {if (maxFraction_ == 0) {df.applyPattern("0E0");} else {df.applyPattern("0."+sharpByPrecision+"E0");}}}return f;} public String format(double v) {if (Double.isNaN(v)) {return "-";}if (v==0) {return "0"; }final double absv = Math.abs(v);if (absv<EXP_DOWN) {return nfBelow_.format(v);}if (absv>EXP_UP) {return nfAbove_.format(v);}return nfNormal_.format(v);}/*** format and higlight the important part (integer part & exponent part) */public String formatHtml(double v) {if (Double.isNaN(v)) {return "-";}return htmlize(format(v));}/*** This is the base alogrithm: create a instance of NumberFormat for the value, then format it. It should* not be used to format a great numbers of value * * We will never use this methode, it is here only to understanding the Algo principal:* * format v to string. precision_ is numbers of digits after decimal. * if EXP_DOWN <= abs(v) <= EXP_UP, display the normal format: 124.45678* otherwise display scientist format with: 1.2345e+30 * * pre-condition: precision >= 1*/@Deprecatedpublic String formatInefficient(double v) {final String sharpByPrecision = Strings.repeat("#", maxFraction_); //if you do not use Guava library, replace with createSharp(precision);final double absv = Math.abs(v);NumberFormat f = NumberFormat.getInstance(Locale.US);//Apply banker's rounding:  this is the rounding mode that statistically minimizes cumulative error when applied repeatedly over a sequence of calculationsf.setRoundingMode(RoundingMode.HALF_EVEN);if (f instanceof DecimalFormat) {DecimalFormat df = (DecimalFormat) f;DecimalFormatSymbols dfs = df.getDecimalFormatSymbols();//set group separator to space instead of commadfs.setGroupingSeparator(' ');//set Exponent symbol to minus 'e' instead of 'E'if (absv>EXP_UP) {dfs.setExponentSeparator("e+"); //force to display the positive sign in the exponent part} else {dfs.setExponentSeparator("e");}df.setDecimalFormatSymbols(dfs);//use exponent format if v is out side of [EXP_DOWN,EXP_UP]if (absv<EXP_DOWN || absv>EXP_UP) {df.applyPattern("0."+sharpByPrecision+"E0");} else {df.applyPattern("#,##0."+sharpByPrecision);}}return f.format(v);}/*** Convert "3.1416e+12" to "<b>3</b>.1416e<b>+12</b>"* It is a html format of a number which highlight the integer and exponent part*/private static String htmlize(String s) {StringBuilder resu = new StringBuilder("<b>");int p1 = s.indexOf('.');if (p1>0) {resu.append(s.substring(0, p1));resu.append("</b>");} else {p1 = 0;}int p2 = s.lastIndexOf('e');if (p2>0) {resu.append(s.substring(p1, p2));resu.append("<b>");resu.append(s.substring(p2, s.length()));resu.append("</b>");} else {resu.append(s.substring(p1, s.length()));if (p1==0){resu.append("</b>");}}return resu.toString();}
}

注意:我使用了GUAVA库中的2个函数。 如果您不使用GUAVA,请自己编写代码:

/*** Equivalent to Strings.repeat("#", n) of the Guava library: */
private static String createSharp(int n) {StringBuilder sb = new StringBuilder(); for (int i=0;i<n;i++) {sb.append('#');}return sb.toString();
}

#4楼

如果您的想法是打印存储为双精度型的整数,就好像它们是整数一样,否则,以最低的必要精度打印双精度型:

public static String fmt(double d)
{if(d == (long) d)return String.format("%d",(long)d);elsereturn String.format("%s",d);
}

产生:

232
0.18
1237875192
4.58
0
1.2345

并且不依赖于字符串操作。


#5楼

String s = String.valueof("your int variable");
while (g.endsWith("0") && g.contains(".")) {g = g.substring(0, g.length() - 1);if (g.endsWith(".")){g = g.substring(0, g.length() - 1);}
}

#6楼

这是实现它的两种方法。 首先,较短(可能更好)的方法是:

public static String formatFloatToString(final float f){final int i=(int)f;if(f==i)return Integer.toString(i);return Float.toString(f);}

这是更长或更糟的方法:

public static String formatFloatToString(final float f){final String s=Float.toString(f);int dotPos=-1;for(int i=0;i<s.length();++i)if(s.charAt(i)=='.'){dotPos=i;break;}if(dotPos==-1)return s;int end=dotPos;for(int i=dotPos+1;i<s.length();++i){final char c=s.charAt(i);if(c!='0')end=i+1;}final String result=s.substring(0,end);return result;}

#7楼

这是一个实际可行的答案(此处结合了不同的答案)

public static String removeTrailingZeros(double f)
{if(f == (int)f) {return String.format("%d", (int)f);}return String.format("%f", f).replaceAll("0*$", "");
}

#8楼

在我的机器上,以下函数比JasonD的答案提供的函数大约快7倍,因为它避免了String.format

public static String prettyPrint(double d) {int i = (int) d;return d == i ? String.valueOf(i) : String.valueOf(d);
}

#9楼

简而言之:

如果要摆脱尾随零和Locale问题,则应使用:

double myValue = 0.00000021d;DecimalFormat df = new DecimalFormat("0", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
df.setMaximumFractionDigits(340); //340 = DecimalFormat.DOUBLE_FRACTION_DIGITSSystem.out.println(df.format(myValue)); //output: 0.00000021

说明:

为什么其他答案不适合我:

  • 如果double小于10 ^ -3或大于或等于10 ^ 7,则Double.toString()System.out.printlnFloatingDecimal.toJavaFormatString使用科学计数法

     double myValue = 0.00000021d; String.format("%s", myvalue); //output: 2.1E-7 
  • 通过使用%f ,默认的十进制精度为6,否则可以对其进行硬编码,但如果小数位数较少,则会导致添加额外的零。 范例:

     double myValue = 0.00000021d; String.format("%.12f", myvalue); //output: 0.000000210000 
  • 通过使用setMaximumFractionDigits(0);%.0f会删除所有十进制精度,这对于整数/长整数很好,但对双精度不是

     double myValue = 0.00000021d; System.out.println(String.format("%.0f", myvalue)); //output: 0 DecimalFormat df = new DecimalFormat("0"); System.out.println(df.format(myValue)); //output: 0 
  • 通过使用DecimalFormat,您是本地依赖的。 在法国语言环境中,小数点分隔符是逗号,而不是点:

     double myValue = 0.00000021d; DecimalFormat df = new DecimalFormat("0"); df.setMaximumFractionDigits(340); System.out.println(df.format(myvalue));//output: 0,00000021 

    使用英语语言环境可确保在程序运行的任何地方都获得小数点

为什么要对setMaximumFractionDigits使用340?

两个原因:

  • setMaximumFractionDigits接受一个整数,但是其实现具有允许的最大数字DecimalFormat.DOUBLE_FRACTION_DIGITS等于340
  • Double.MIN_VALUE = 4.9E-324所以使用340位数字时,请确保不要舍入双精度和宽松精度

#10楼

为什么不:

if (d % 1.0 != 0)return String.format("%s", d);
elsereturn String.format("%.0f",d);

这应该可以使用Double支持的极限值。 产量:

0.12
12
12.144252
0

#11楼

请注意, String.format(format, args...)依赖于语言环境的,因为它使用用户的默认语言环境进行格式化即,可能使用逗号,甚至内部空格如123 456,789123,456.789 ,这可能与您的不完全相同期望。

您可能更喜欢使用String.format((Locale)null, format, args...)

例如,

    double f = 123456.789d;System.out.println(String.format(Locale.FRANCE,"%f",f));System.out.println(String.format(Locale.GERMANY,"%f",f));System.out.println(String.format(Locale.US,"%f",f));

版画

123456,789000
123456,789000
123456.789000

这就是String.format(format, args...)在不同国家/地区的String.format(format, args...)

编辑好的,因为已经有关于形式的讨论:

    res += stripFpZeroes(String.format((Locale) null, (nDigits!=0 ? "%."+nDigits+"f" : "%f"), value));...protected static String stripFpZeroes(String fpnumber) {int n = fpnumber.indexOf('.');if (n == -1) {return fpnumber;}if (n < 2) {n = 2;}String s = fpnumber;while (s.length() > n && s.endsWith("0")) {s = s.substring(0, s.length()-1);}return s;
}

#12楼

答案迟了,但是...

您说您选择使用双精度类型存储数字。 我认为这可能是问题的根源,因为它迫使您将整数存储为双精度型(因此丢失了有关值性质的初始信息)。 将数字存储在Number类(Double和Integer的超类)的实例中并依靠多态性确定每个数字的正确格式怎么办?

我知道,因此重构整个代码可能是不可接受的,但是它可以在不进行额外代码/广播/解析的情况下产生所需的输出。

例:

import java.util.ArrayList;
import java.util.List;public class UseMixedNumbers {public static void main(String[] args) {List<Number> listNumbers = new ArrayList<Number>();listNumbers.add(232);listNumbers.add(0.18);listNumbers.add(1237875192);listNumbers.add(4.58);listNumbers.add(0);listNumbers.add(1.2345);for (Number number : listNumbers) {System.out.println(number);}}}

将产生以下输出:

232
0.18
1237875192
4.58
0
1.2345

#13楼

if (d == Math.floor(d)) {return String.format("%.0f", d);
} else {return Double.toString(d);
}

#14楼

我的2美分:

if(n % 1 == 0) {return String.format(Locale.US, "%.0f", n));
} else {return String.format(Locale.US, "%.1f", n));
}

#15楼

这个我可以很好地完成工作,我知道这个话题很旧,但是直到遇到这个问题我一直在努力解决同样的问题。 我希望有人觉得它有用。

    public static String removeZero(double number) {DecimalFormat format = new DecimalFormat("#.###########");return format.format(number);}

#16楼

new DecimalFormat("#.##").format(1.199); //"1.2"

正如评论中指出的那样,这不是对原始问题的正确答案。
也就是说,这是一种非常有用的数字格式,无需多余的尾随零。


#17楼

new DecimalFormat("00.#").format(20.236)
//out =20.2new DecimalFormat("00.#").format(2.236)
//out =02.2
  1. 0为最小位数
  2. 渲染数字

#18楼

public static String fmt(double d) {String val = Double.toString(d);String[] valArray = val.split("\\.");long valLong = 0;if(valArray.length == 2){valLong = Long.parseLong(valArray[1]);}if (valLong == 0)return String.format("%d", (long) d);elsereturn String.format("%s", d);
}

我不得不使用这个原因d == (long)d在声纳报告中给了我违反


#19楼

使用DecimalFormatsetMinimumFractionDigits(0)


#20楼

这是我想出的:

  private static String format(final double dbl) {return dbl % 1 != 0 ? String.valueOf(dbl) : String.valueOf((int) dbl);}

简单的一个内衬,仅在确实需要时才强制转换为int


#21楼

使用分组,舍入,没有不必要的零(双精度)格式化价格。

规则:

  1. 末尾没有零( 2.0000 = 2; 1.0100000 = 1.01
  2. 点后最多两位数( 2.010 = 2.01; 0.20 = 0.2
  3. 在一个点后的第二个数字后舍入( 1.994 = 1.99; 1.995 = 2; 1.006 = 1.01; 0.0006 -> 0
  4. 返回0null/-0 = 0
  5. $= $56/-$56
  6. 分组( 101101.02 = $101,101.02

更多示例:

-99.985 = -$99.99

10 = $10

10.00 = $10

20.01000089 = $20.01

用Kotlin编写,作为Double的有趣扩展(在Android中使用),但可以轻松转换为Java,因为使用了Java类。

/*** 23.0 -> $23** 23.1 -> $23.1** 23.01 -> $23.01** 23.99 -> $23.99** 23.999 -> $24** -0.0 -> $0** -5.00 -> -$5** -5.019 -> -$5.02*/
fun Double?.formatUserAsSum(): String {return when {this == null || this == 0.0 -> "$0"this % 1 == 0.0 -> DecimalFormat("$#,##0;-$#,##0").format(this)else -> DecimalFormat("$#,##0.##;-$#,##0.##").format(this)}
}

如何使用:

var yourDouble: Double? = -20.00
println(yourDouble.formatUserAsSum()) // will print -$20yourDouble = null
println(yourDouble.formatUserAsSum()) // will print $0

关于DecimalFormat : https : //docs.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html


#22楼

这可能很明显,但有时注释会有所帮助。 如果不想更改浮位数,则可以使用println

System.out.println("YOUR STRING" + YOUR_DOUBLE_VARIABLE);

#23楼

w,没关系。

由于字符串操作而导致的性能损失为零。

这是在%f之后修剪结尾的代码

private static String trimTrailingZeros(String number) {if(!number.contains(".")) {return number;}return number.replaceAll("\\.?0*$", "");
}

#24楼

String s = "1.210000";
while (s.endsWith("0")){s = (s.substring(0, s.length() - 1));
}

这将使字符串的尾部下降0-s。

如何将浮点数很好地格式化为String而没有不必要的十进制0?相关推荐

  1. 如何在R中将数字格式化为百分比

    作为 R 的新手,曾经让我感到困惑的一件事是如何将数字格式化为打印的百分比. 例如,显示0.12345为12.345%.我有许多解决方法,但这些似乎都不是"新手友好".例如: se ...

  2. C#中将long浮点数格式化为{H:min:s.ms}格式的字符串的方法

    场景 表示时间的数据格式为浮点数,如下: 需要将其格式化为{H:min:s.ms}格式的字符串,效果如下: 注: 博客主页: https://blog.csdn.net/badao_liumang_q ...

  3. android设置为存储设备,我可以从格式化为内部存储器的Android SD卡或USB驱动器中恢复数据吗? | MOS86...

    几年前,Android引入了使用外部存储作为内部存储的功能,但这将SD卡和手机联系在一起. 如果出现问题,您将可以取回卡上的所有数据. 如果将SD卡或USB驱动器格式化为内部存储设备,则手机的原始存储 ...

  4. android ext3 格式化,怎样将TF卡格式化为EXT分区?

    App2SD就是将Android系统中的程序安装在SD卡中,需要将内存卡分区为Linux的EXT分区,那么怎样将TF卡格式化为EXT分区?Android手机网总结了将TF卡格式化为EXT分区的详细步骤 ...

  5. html手机号输入框,手机号输入框自动格式化为344

    写在前面 相信大家已经看过某些手机号的输入框在输入的时候,手机号是3 4 4格式,即 输入一个手机号时,会隔成 159 8888 3333 这样的输入框.笔者也实现了一个这样的组件,这个组件的特点是: ...

  6. 将sd卡格式化为ext4格式并挂载

    1. 介绍 uboot加载内核时会从sd中读取内核镜像,和老版本的uboot不同,新版本的uboot支持文件系统,直接将内核镜像复制到sd卡中,然后uboot启动时就会访问sd卡的文件系统,找到内核镜 ...

  7. 重装系统 U盘安装 提示Windows检测到EFI系统分区格式化为NIFS,将EFI系统分区格式化为FAT32,然后重新启动安装

    系统状态:无法进入操作系统,原来是windows10系统,后崩溃,准备重装系统. 硬件状态:双硬盘:固态硬盘+机械硬盘. 重装系统方式:U盘刻录方式,U盘内部刻录了官方Windows10系统.准备重装 ...

  8. U盘或SD卡格式化为ext格式

    U盘或SD卡格式化为ext2.3.4格式 目录 无 简介 一.选择方式 1.第一种方法:电脑中使用的操作系统是Linux或者Linux核心的其他操作系统(例如Ubuntu.红旗操作系统),将读卡器插入 ...

  9. linux 磁盘格式化 恢复数据,从格式化为 exfat 的损坏 U 盘上恢复数据的记录

    把一个格式化为 exfat 格式的 64GB U 盘放到一个老旧的 Android 平板上用了一下,结果就无法识别了.在电脑上也是无法用,Windows 提示需要格式化,Linux 无法挂载但是可以显 ...

最新文章

  1. 通过COLA看应用架构
  2. Windows系统运维转linux系统运维的经历
  3. mysql 1146错误
  4. 开放下载!阿里云开发者学堂配套教材《JVM实战》
  5. 《HTML、CSS、JavaScript 网页制作从入门到精通》——第6章 使用表格
  6. centos静默安装oracle关于报错UnsatisfiedLinkError exception loading native library:njni10
  7. 初学者指南:如何为Red Hat Process Automation Manager配置电子邮件服务任务
  8. 无线网状网、Zigbee、RFID三种技术分析
  9. 4,表查询语法,表连接,子查询
  10. c语言增加动态分配的存储空间吗,C语言 关于内存动态分配问题
  11. 运算符优先级(图表)
  12. mysql自增字段AUTO_INCREMENT重排或归零
  13. ISAPI Rewrite 2 规则中文版
  14. 利用Linq对集合元素合并、去重复处理
  15. Python 猜数字小游戏 (带闯关关卡)
  16. bind9 dlz mysql_源码安装Bind 9.10 正式版 开启DLZ数据库支持 和 数据库view查询
  17. Python课后作业 2. 分治法找假币 ----(第八次作业)
  18. win10计算机添加右键菜单,win10清理鼠标右键菜单提升电脑速度的方法
  19. 亿赛通携手湖北省勘察设计协会 共建数据安全
  20. 【PyQt5】孩子要上小学了,写个软件做练口算吧!

热门文章

  1. 2020年总结以及21年规划
  2. Android 使用Vector 画图详解
  3. LayoutInflater.Factory 妙用
  4. android圆角ImageView的几种实现方式
  5. b站前端大佬_最强UP主:罗翔老师,你凭什么打败B站千万粉大佬老番茄?
  6. Flutter开发之ListView下拉刷新上拉加载更多(35)
  7. Flutter开发之搭建Flutter开发环境(三)
  8. (0078)iOS开发之支付宝集成:客户端签名与验证
  9. 虚拟机VMware操作系统安装
  10. Xshell登录Ubuntu12.04