如何打印双在Android的两位小数? [英] How to print a double with two decimals in Android?

查看:151
本文介绍了如何打印双在Android的两位小数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许这是一个愚蠢的问题,但我不能想怎么解决它,如果它不是创建一个方法。也许有一个自然的方式来做到这一点,就像在C为例。这里的问题:

我有一个变种:

 双A;
 

和我想只有2或3位小数表现出来。当我试图表现出来:

  Text.setText(价值一:+将String.valueOf(一));
 

它给这样的:

  

的价值:5.234966145

和我想只是

  

值:5.23

在不改变的实际值,因此它显示的大致数目,但工作原理与实数。

解决方案

  Text.setText(的String.Format(一个价值:%.2f,一));
 

Maybe this is a silly question, but I cannot guess how to solve it if it's not creating a method. Maybe there's a "natural way" to do it, like in C for example. Here's the problem:

I have a var:

double a;

And I want to show it only with 2 or 3 decimals. When I try to show it:

Text.setText("Value of a: " + String.valueOf(a));

It gives something like:

Value of a: 5.234966145

And i would want just

Value of a: 5.23

Without changing the real value of a so it shows the approximate number but works with the real number.

解决方案

Text.setText( String.format( "Value of a: %.2f", a ) );

这篇关于如何打印双在Android的两位小数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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