限制双精度的执行方式 [英] Performing way to limit double accuracy

查看:82
本文介绍了限制双精度的执行方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要管理以下范围内的数字:

I want manage numbers on a range from:

0,001999,999

出于表示形式的原因,我想降低一些准确性,仅保留数字的3个最重要的数字.

For representation reasons, I want to drop some of the accuracy keeping only the 3 most important digits of the number.

对于数字123,12,我希望结果为123.

For the number 123,12 I expect the result 123.

对于数字12,123,我希望结果为12,1.

For the number 12,123 I expect the result 12,1.

对于数字0,001,我希望结果为0,001.

For the number 0,001 I expect the result 0,001.

我想到的最好的解决方案是将数字转换为字符串,然后再次以这种方式加倍:

The best solution I thought of is transforming the number into a String, and back again to double, this way:

 number = number*1000;
 String s = new String(number);
 s = s.substr(0, 3) + "000";
 number = Double.parseDouble(s);
 number = number/1000;

这可以完成工作,但是它看起来既性能不好又不优雅. 还有其他更聪明的选择吗? 谢谢!

This does the job but it looks both poorly performing and not elegant. Any more clever alternative? Thank you!

推荐答案

也许使用正则表达式使代码更简洁?

Perhaps use this RegEx to make the code more concise?

^[,0]{0,6}(\d{3}|\d{2},\d|\d,\d{2})

这篇关于限制双精度的执行方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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