如何强制将浮点数保留两位小数(.00)

huangapple go评论68阅读模式
英文:

How to force a float to get stored with two decimals (.00)

问题

我所需的:我需要在Java(11)中存储一个保留两位小数的浮点数。

我所做的:我使用了BigDecimal类,并没有出现问题,即使小数部分是.00,比例也如预期一样。

我的问题是什么:当我使用.floatValue()将BigDecimal转换为float时,如果小数部分是.00,它会去掉尾随的0。

一些示例

  1. 2.45(Big dec)被转换为浮点数2.45
  2. 2.00(Big dec)被转换为浮点数2.0 ==> 我希望是2.00

有解决方案吗?谢谢!

编辑:将浮点数作为字符串输出不是我想要的,我需要将变量存储为浮点数。

我快速检查了DecimalFormat,但目前我只找到了将其格式化为字符串的方法。

编辑2:我正在开发一个REST API,我想要返回一个JSON,其中必须将价格输出为浮点数(否则我会将其返回为BigDecimal)。我希望每次返回带有2位小数的价格。除了小数部分是.00(.01到.99的情况正常工作)的情况外,它在所有情况下都有效。JSON中的Float类型是我无法更改的约束。

英文:

What I need : I need to store a Float with two decimals in java (11)

What I did : I used the BigDecimal class with no problems, the scale is as expected even when the decimal portion is .00

What is my problem : When I convert the BigDecimal to a float with .floatValue() it removes the trailing 0 if the decimal portion is .00

A few examples

  1. 2.45 (Big dec) gets converted to 2.45 as a Float
  2. 2.00 (Big dec) gets converted to 2.0 as a Float ==> I want 2.00

Any solution ? Thanks !

EDIT : Outputting the float as a string is not what I want, I need to store the variable as a Float

I checked quickly DecimalFormat but at the moment I only found methods that format it as a string.

EDIT2 : I am working on a REST api, I want to return a JSON which has to output a price as a Float (else I would have returned it as a big decimal) I want to return the price with 2 decimals every time. It works in all cases except when the decimal portion is .00 (.01 to .99 works fine) as explained above. The Float type in the JSON is a constraint that I cannot change.

答案1

得分: 1

你无法存储带有两位小数的浮点数。这不是浮点数的工作方式。它们是数字的二进制表示,而不是十进制表示。

你可以将浮点数格式化为带有两位小数。

英文:

You can't store a float with two decimals. It's not how floats work. They're a binary representation of a number, not a decimal one.

You can format a float with two decimals.

huangapple
  • 本文由 发表于 2020年9月20日 00:15:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/63970878.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定