在 Perl 中,如何限制小数点后的位数但没有尾随零? [英] In Perl, how can I limit the number of places after the decimal point but have no trailing zeroes?

查看:57
本文介绍了在 Perl 中,如何限制小数点后的位数但没有尾随零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题类似于从浮动中删除尾随'.0'", 但对于 Perl 和小数点后的最大位数.

This question is similar to "dropping trailing ‘.0’ from floats", but for Perl and with a maximum number of digits after the decimal.

我正在寻找一种将数字转换为字符串格式的方法,去掉任何多余的0",不仅包括小数点之后.并且仍然具有最大数量的数字,例如3

I'm looking for a way to convert numbers to string format, dropping any redundant '0', including not just right after the decimal. And still with a maximum number of digital, e.g. 3

输入数据是浮点数.期望输出:

The input data is floats. Desired output:

0         -> 0
0.1       -> 0.1
0.11      -> 0.11
0.111     -> 0.111
0.1111111 -> 0.111

推荐答案

您也可以使用 Math::Round 这样做:

You can also use Math::Round to do this:

$ perl -MMath::Round=nearest -e 'print nearest(.001, 0.1), "\n"'
0.1
$ perl -MMath::Round=nearest -e 'print nearest(.001, 0.11111), "\n"'
0.111

这篇关于在 Perl 中,如何限制小数点后的位数但没有尾随零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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