c# – 将int转换为十进制选择放置小数位的位置
发布时间:2020-12-15 19:40:55 所属栏目:百科 来源:网络整理
导读:我有一个有趣的问题,我需要将int转换为小数. 例如给出: int number = 2423;decimal convertedNumber = Int2Dec(number,2);// decimal should equal 24.23decimal convertedNumber2 = Int2Dec(number,3);// decimal should equal 2.423 我玩过,这个功能有效,
我有一个有趣的问题,我需要将int转换为小数.
例如给出: int number = 2423; decimal convertedNumber = Int2Dec(number,2); // decimal should equal 24.23 decimal convertedNumber2 = Int2Dec(number,3); // decimal should equal 2.423 我玩过,这个功能有效,我只是讨厌我必须创建一个字符串并将其转换为小数,它似乎不是很有效: decimal IntToDecConverter(int number,int precision) { decimal percisionNumber = Convert.ToDecimal("1".PadRight(precision+1,'0')); return Convert.ToDecimal(number / percisionNumber); } 解决方法
由于你试图使数字变小,你不能除以10(小数点后1位),100(小数点后2位),1000(小数点后3位)等.
注意模式了吗?当我们增加小数点右边的数字时,我们也增加了被分割的初始值(小数点后1位数为10,小数点后2位数为100,等等)10倍. 因此,模式表示我们正在处理10的幂(Math.Pow(10,x)). 给定输入(小数位数)进行转换. 例: int x = 1956; int powBy=3; decimal d = x/(decimal)Math.Pow(10.00,powBy); //from 1956 to 1.956 based on powBy 话虽如此,将其包装成一个函数: decimal IntToDec(int x,int powBy) { return x/(decimal)Math.Pow(10.00,powBy); } 这样称呼它: decimal d = IntToDec(1956,3); 走向相反的方向 如果有人说他们想要像19.56这样的小数并将其转换为int,那么你也可以做相反的事情.你仍然使用Pow机制,但不是分开你会成倍增加. double d=19.56; int powBy=2; double n = d*Math.Pow(10,powBy); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |