简体   繁体   English

删除双精度的最后一个十进制值

[英]Delete last decimal value in a double

I am making a calculator in C#. 我正在用C#制作计算器。 I save the input from the user as a double. 我将来自用户的输入保存为双精度。

I use the following code to delete the last entered number in a double withour decimals. 我使用以下代码删除带小数点的双精度数字中最后输入的数字。

i = (i - (i % 10)) / 10;

This wil delete the last number. 这将删除最后一个数字。

12345 wil become 1234 12345将变成1234


What I can't figuere out is how to make this happen for decimal values. 我无法确定的是如何使十进制值发生这种情况。

2134.765 must become 2134.76 2134.765必须成为2134.76

my program uses a var to see if a point has been put in so I only need the math to delete the last number. 我的程序使用var来查看是否已插入点,因此我只需要数学运算即可删除最后一个数字。

Since you're dealing with character input and not math yet, just keep your input as a string until you need to perform an operation on it . 由于您正在处理字符输入而不是数学运算 ,因此只需将输入保留为字符串, 直到需要对其进行操作即可 Then removing the last character is as simple as 然后删除最后一个字符就像

input = input.Substring(0,input.Length-1);

Otherwise you have to deal with ambiguous situations like: 否则,您必须处理模棱两可的情况,例如:

  • What if the last character is a decimal point? 如果最后一个字符是小数点怎么办?
  • What if one or more trailing zeros have been entered? 如果输入了一个或多个尾随零,该怎么办?
  • Has a decimal point been entered (you say you already track this) 是否输入了小数点(您说您已经对此进行了跟踪)

The easiest way would probably be to use your own number format - you want to keep the values decimal anyway. 最简单的方法可能是使用您自己的数字格式-无论如何您都希望将值保留为十进制。 double is a terrible choice for that. double是一个糟糕的选择。 At the very least, use a decimal so that you're guaranteed the decimal representation of the number. 至少要使用decimal以便保证数字的小数点表示。

If you really always only wanna delete the last digit in the number I would use a trick and convert the number to string remove the last char and back. 如果您真的总是只想删除数字中的最后一位,我会用把戏并将数字转换为字符串,然后删除最后一个字符并返回。

var number = 123,456;
var strNumber = number;
strNumber.Remove(strNumber.Length - 1);
number = double.parse(strNumber);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM