确定的输入数的十进制精度 [英] Determine the decimal precision of an input number

查看:162
本文介绍了确定的输入数的十进制精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个有趣的问题是,我们需要确定一个用户输入(文本框)的小数精度。基本上,我们需要知道输入小数的数量,然后返回一个精度数,这是最好的实施例说明

We have an interesting problem were we need to determine the decimal precision of a users input (textbox). Essentially we need to know the number of decimal places entered and then return a precision number, this is best illustrated with examples:

4500输入将产生的结果1搜索
4500.1进入将产生一个结果0.1结果
4500.00进入将产生一个结果0.01结果
4500.450进入将产生一个结果0.001

4500 entered will yield a result 1
4500.1 entered will yield a result 0.1
4500.00 entered will yield a result 0.01
4500.450 entered will yield a result 0.001

我们正在考虑用字符串的工作,找到小数点分隔符,然后计算结果。 。只是想知道如果有一个更简单的解决这个

We are thinking to work with the string, finding the decimal separator and then calculating the result. Just wondering if there is an easier solution to this.

推荐答案

我觉得你应该做你的建议 - 使用的位置小数点。 。明显的缺点可能是你要想想你自己internatialisation

I think you should just do what you suggested - use the position of the decimal point. Obvious drawback might be that you have to think about internatialisation yourself.

var decimalSeparator = NumberFormatInfo.CurrentInfo.CurrencyDecimalSeparator;

var position = input.IndexOf(decimalSeparator);

var precision = (position == -1) ? 0 : input.Length - position - 1;

// This may be quite unprecise.
var result = Math.Pow(0.1, precision);

有是你可以尝试另一种东西 - 小数键入存储内部precission值。因此,你可以使用 Deciml.TryParse()并检查返回值。也许解析算法维护输入的precission。

There is another thing you could try - the Decimal type stores a internal precission value. Therefore you could use Deciml.TryParse() and inspect the returned value. Maybe the parsing algorithm maintains the precission of the input.

最后,我会建议不使用浮点数来试一下。只是分析输入将会移除尾随零的任何信息。所以,你必须添加人工非零数字保护他们或做类似的把戏。您可能会遇到的问题precission。最后发现基于一个浮点数precission并不简单,太。我看到一些丑陋的数学或一环十每次迭代倍增,直到不再有任何小数部分。并且循环带有新precission问题...

Finally I would suggest not to try something using floating point numbers. Just parsing the input will remove any information about trailing zeros. So you have to add an artifical non-zero digit to preserve them or do similar tricks. You might run into precission issues. Finally finding the precission based on a floating point number is not simple, too. I see some ugly math or a loop multiplying with ten every iteration until there is no longer any fractional part. And the loop comes with new precission issues...

更新

解析成deciaml作品。硒 Decimal.GetBits() < 。/ A>详情

Parsing into a deciaml works. Se Decimal.GetBits() for details.

var input = "123.4560";

var number = Decimal.Parse(input);

// Will be 4.
var precision = (Decimal.GetBits(number)[3] >> 16) & 0x000000FF;



从这里使用 Math.Pow(0.1,精度)是直线前进。

这篇关于确定的输入数的十进制精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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