在 VB.NET 中拆分“十进制”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/362441/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Split a 'Decimal' in VB.NET
提问by chillysapien
I am sure this is a very simple problem, but I am new to VB.NET, so I am having an issue with it.
我确信这是一个非常简单的问题,但我是 VB.NET 的新手,所以我遇到了问题。
I have a Decimal
variable, and I need to split it into two separate variables, one containing the integer part, and one containing the fractional part.
我有一个Decimal
变量,我需要把它分成两个单独的变量,一个包含整数部分,一个包含小数部分。
For example, for x = 12.34 you would end up with a y = 12 and a z = 0.34.
例如,对于 x = 12.34,您最终会得到 ay = 12 和 az = 0.34。
Is there a nice built-in functions to do this or do I have to try and work it out manually?
有没有很好的内置函数来做到这一点,还是我必须尝试手动解决?
回答by Jon Skeet
You can use Math.Truncate(decimal)and then subtract that from the original. Be aware that that will give you a negative value for both parts if the input is decimal (e.g. -1.5 => -1, -.5)
您可以使用Math.Truncate(decimal)然后从原始值中减去它。请注意,如果输入是十进制(例如 -1.5 => -1, -.5),这将为您提供两个部分的负值
EDIT: Here's a version of Eduardo's code which uses decimal throughout:
编辑:这是 Eduardo 代码的一个版本,它始终使用十进制:
Sub SplitDecimal(ByVal number As Decimal, ByRef wholePart As Decimal, _
ByRef fractionalPart As Decimal)
wholePart = Math.Truncate(number)
fractionalPart = number - wholePart
End Sub
回答by Eduardo Molteni
(As Jon Skeet says), beware that the integer part of a decimal can be greater than an integer, but this function will get you the idea.
(正如 Jon Skeet 所说),请注意小数的整数部分可能大于整数,但是这个函数会让你明白。
Sub SlipDecimal(ByVal Number As Decimal, ByRef IntegerPart As Integer, _
ByRef DecimalPart As Decimal)
IntegerPart = Int(Number)
DecimalPart = Number - IntegerPart
End Sub
Use the Jon version if you are using big numbers.
如果您使用大数字,请使用 Jon 版本。
回答by Ram
Simply:
简单地:
DecimalNumber - Int(DecimalNumber)