Java:格式为double,带小数 [英] Java: Format double with decimals

查看:195
本文介绍了Java:格式为double,带小数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在目标CI中,使用此代码格式化一个值,使得零小数的值将被写入无小数位,小数位的值将被写入一个小数:

  CGFloat值= 1.5; 
return [NSString stringWithFormat:@%。* f,(value!= floor(value)),value];

//如果value == 1.5,输出将为1.5
//如果value == 1.0,输出将为1

我需要为Java中的双重值做同样的事情,我尝试了以下操作,但这不起作用:

  return String.format(%。* f,(value!= Math.floor(value)),value); 


解决方案

查看如何打印不带逗号的Double 。这肯定会为您提供一些想法。



正确的是,这将会执行

  DecimalFormat.getInstance()。format(1.5)
DecimalFormat.getInstance()。format(1.0)


In Objective C I have been using this code to format a value so that a value with zero decimals will be written without decimals and a value with decimals will be written with one decimal:

CGFloat value = 1.5;
return [NSString stringWithFormat:@"%.*f",(value != floor(value)),value];

//If value == 1.5 the output will be 1.5
//If value == 1.0 the output will be 1

I need to do the same thing for a double value in Java, I tried the following but that is not working:

return String.format("%.*f",(value != Math.floor(value)),value);

解决方案

Look at how to print a Double without commas. This will definitely provide you some idea.

Precisely, this will do

DecimalFormat.getInstance().format(1.5)
DecimalFormat.getInstance().format(1.0)

这篇关于Java:格式为double,带小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆