声明 double 类型变量时格式化它

发布于 2025-01-18 13:17:15 字数 510 浏览 3 评论 0原文

我知道将双重变量格式化为十进制位置的x#的多种方法。话虽如此:

static double currentSelectedPrice = 0.00; //format to 2 decimal places
static double usercashBalance = 0.00

以下代码通过我的代码在不同的位置找到。我不想浏览代码并格式化(CurrentSelectedPrice -userCashbalance)的结果,

if(usercashBalance < currentSelectedPrice)                
{
      System.out.println("Remaing: $" + (currentSelectedPrice - usercashBalance));
      continue;
}

在声明它们时已经格式化了这些变量是理想的选择(因此,其操作的输出也已格式化) 。 有可能吗?

I'm aware of the many ways of formatting a double variable to X # of decimal places. With that being said:

static double currentSelectedPrice = 0.00; //format to 2 decimal places
static double usercashBalance = 0.00

The code below is found at different locations through my code. I do not want to go through the code and format the result of (currentSelectedPrice - usercashBalance)

if(usercashBalance < currentSelectedPrice)                
{
      System.out.println("Remaing: 
quot; + (currentSelectedPrice - usercashBalance));
      continue;
}

It would be ideal to already have those variables formatted when declaring them (so the output of its operations is also formatted).
Is that possible?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

向地狱狂奔 2025-01-25 13:17:15

double(或double)没有格式信息!

它只是值的浮点表示。

这两条线导致d的相同值:

double d = 1;
double d = 1.00000000;

但是,您可以控制双重渲染/格式的方式,例如,

String formatted = String.format("%,.4f", d);

用4个小数位置呈现双重值。


提示:如果将所有货币价值存储为int美分的,并将其呈现为十进制美元,那么您的大多数问题都会消失。

A double (or Double) has no formatting information!

It is just a floating point representation of a value.

These two lines result in identical values for d:

double d = 1;
double d = 1.00000000;

You can however control how a double is rendered/formatted, eg

String formatted = String.format("%,.4f", d);

Renders the double value with 4 decimal places.


Tip: if you store all currency values as an int of cents, and render it as decimal dollars, most of your problems disappear.

无声静候 2025-01-25 13:17:15

我会尝试这样的东西

if(usercashBalance < currentSelectedPrice)                
{
    System.out.printf("Remaing: $%.<x>f", (currentSelectedPrice - usercashBalance));
    continue;
}

x,指示您要从结果打印的小数数量

I would try something like this

if(usercashBalance < currentSelectedPrice)                
{
    System.out.printf("Remaing: $%.<x>f", (currentSelectedPrice - usercashBalance));
    continue;
}

x indicating the number of decimals you want to print from your result

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文