grovvy 字符串保留两位小数
时间: 2023-09-04 18:12:35 浏览: 477
在Groovy中,如果你想要将一个数字保留两位小数并将其转换为字符串,你可以使用`String.format()`方法或使用`NumberFormat`类来实现。以下是两种方法的示例代码:
方法1:使用`String.format()`
```groovy
def num = 3.1415926
def formattedString = String.format("%.2f", num)
println(formattedString)
```
输出:
```
3.14
```
方法2:使用`NumberFormat`
```groovy
import java.text.NumberFormat
def num = 3.1415926
def numberFormat = NumberFormat.getNumberInstance()
numberFormat.setMaximumFractionDigits(2)
def formattedString = numberFormat.format(num)
println(formattedString)
```
输出:
```
3.14
```
希望这可以帮助到你!<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [groovy 字符串截取最后一个_python数据类型总结——数字和字符串](https://blog.csdn.net/weixin_39721853/article/details/110252112)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
- *2* *3* [groovy风格字符串截取、赋值、拼接](https://blog.csdn.net/alittleyatou/article/details/82591654)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文