简体   繁体   English

简单干净的Java float到字符串转换

[英]Simple and clean java float to string conversion

This is a very simple question, but I'm amazed on how difficult it has been to answer. 这是一个非常简单的问题,但我对回答的难度感到惊讶。 Even the documentation didn't give a clear and straight answer. 甚至文档也没有给出明确而直接的答案。

You see, I'm simply trying to convert a simple float to a string such that the result only has one decimal digit. 您看,我只是在尝试将简单的float转换为字符串,以使结果仅包含一个十进制数字。 For example: 例如:

String myfloatstring = "";
float myfloat = 33.33;
myfloatstring = Float.toString(myfloat);

This does indeed return "33.33". 实际上确实返回“ 33.33”。 This is fine, except I'm looking for a way to get it to truncate the decimal to "33.3". 很好,不过我正在寻找一种方法来将小数位截断为“ 33.3”。 It also needs to impose a decimal whenever a whole number is put in. If myfloat was 10, for example, it would need to display as "10.0". 每当输入整数时,它都还必须加上小数点。例如,如果myfloat为10,则它将显示为“ 10.0”。 Oddly not as simple as it sounds. 奇怪的是,听起来并不简单。

Any advice you can give me would be greatly appreciated. 您能给我的任何建议将不胜感激。

EDIT #1: 编辑#1:

For the moment, I'm not concerned with digits to the left of the decimal point. 目前,我不关心小数点左边的数字。

System.out.println(String.format("%.1g%n", 0.9425));
System.out.println(String.format("%.1g%n", 0.9525));
System.out.println(String.format( "%.1f", 10.9125));

returns: 收益:

0.9
1
10.9

Use the third example for your case 使用第三个例子

Stupid roundabout way of doing it: 愚蠢的回旋处:

float myFloat = 33.33f;
int tenTimesFloat = (int) (myFloat * 10); // 333
String result = (tenTimesFloat / 10) + "." + (tenTimesFloat % 10); // 33.3

Note that this truncates the number, so 10.99 would convert to 10.9 . 请注意,这会截断数字,因此10.99将转换为10.9 To round, use Math.round(myFloat * 10) instead of (int) (myFloat * 10) . 要进行舍入,请使用Math.round(myFloat * 10)而不是(int) (myFloat * 10) Also, this only works for float values that are between Integer.MAX_VALUE/10 and Integer.MIN_VALUE/10 . 同样,这仅适用于介于Integer.MAX_VALUE/10Integer.MIN_VALUE/10之间的浮点值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM