我在浮点数后有一个15位数的数字,我需要提取第15位数并使用它.如何在C#中做到这一点 [英] I have a number with 15 digit after floating point and I need to extract 15th digit and use it. How a con do that in C#

查看:171
本文介绍了我在浮点数后有一个15位数的数字,我需要提取第15位数并使用它.如何在C#中做到这一点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写程序,需要处理输出的最后一位,并以二进制形式显示此位,但是我需要提取最后一位然后使用它.我不知道该怎么办.

我尝试过的事情:

我尝试用C#编写代码来解决此问题

I write the program and need to work with last digit of output and display this digit in binary but I need to extract that last digit and then working with it . I do not know how I can do that.

What I have tried:

i try to write the code in c# for solve this problem

推荐答案

那将不容易-C#中的double仅具有15〜16位精度: double(C#参考)| Microsoft文档 [ ^ ],因此正常的乘法并删除整数部分不起作用.实际上,很有可能根本没有存储浮点数后的第15位"-请记住,浮点数数字是二进制存储的数据的表示形式,不一定准确.
一种实现方法是强力和无知"方法:将其转换为字符串,并从中获取数字.

但是更好的解决方案是准确地查看从中得到的数字,并查看其产生方式-我的猜测是输入数据的精度不是15位数字,因此该值不太可能
That''s not going to be easy - a double in C# only has 15~16 digit precision: double (C# Reference) | Microsoft Docs[^] so the normal "multiply and remove teh integer part is not goign to work. In fact, it quite likely that the "15th digit after the float point" is not stored at all - bear in mind that floating point numbers are representations of binary stored data, and are not necesssarily accurate.
One way to do it is a "brute force and ignorance" approach: convert it to a string, and get the digits from that.

But a better solution is to look at exactly what you get the number from, and see how it''s generated - my guess would be that the input data isn''t 15 digit accurate, so it''s unlikely that the value you are playing with is really accurate at that precision.


我找到了最佳解决方案,将数字转换为字符串,然后使用序列函数提取最后一个字符,然后将其转换为整数.如果a = 0.1245378,则整数等于8.

I find the best solution by convert the number to string then by using the sequence function extract the last character then convert it to integer. if a=0.1245378 then the integer become equal 8.

string s = Convert.ToString(a);
string l = s.Substring(s.Length -1);
int integer = Convert.ToInt16(l);


这篇关于我在浮点数后有一个15位数的数字,我需要提取第15位数并使用它.如何在C#中做到这一点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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