KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Creating a Real from an Integer or Decimal
PRODUCT: 4D | VERSION: 11.4 | PLATFORM: Mac & Win
Published On: June 24, 2009

In the 4D Language reference it is shown how to extract the integer and the decimal part of a real number by using Int and Dec commands.

This tip explains the reverse process, creating a real number from two numbers:

The first example is when both numbers are stored as strings. The goal is to keep all leading zeros in the decimal part:

C_TEXT($integerPart; $decimalPart; $stringNumber)
C_REAL($realNumber)
C_INTEGER($power)

$integerPart:="-0"
$decimalPart:="0000123"

$power:=Length($decimalPart)
$stringNumber:=$integerPart + $decimalPart
$realNumber:=Num($stringNumber)*(10^-$power)


Afrer running this method, the value of $realNumber will be equal to -0.0000123. This method works regardless of the local settings for separators. For example, European formats use the "," character as the decimal separator while American formats use the "." character. Since the string is created as a whole number and not a decimal, then divided, this issue is handled by the OS.

The second example is when both numbers are stored as integers. In this case you cannot have leading zeroes:

C_LONGINT($integerPart; $decimalPart)
C_TEXT($stringIntPart; $stringDecPart)

$integerPart:=5
$decimalPart:=123

$stringIntPart:=String($integerPart)
$stringDecPart:=String($decimalPart)


Once you have the numbers in String format you can use the first example to create a Real.

Commented by Atanas Atanassov on July 17, 2009 at 10:02 AM
In the second example where both numbers are integers, converting them to strings is not necessary! The formula will be cahged to: $realNumber:=$integerPart+($decimalPart*(10^-$power))
Commented by Thomas Fitch on June 24, 2009 at 4:36 PM
There are actually many different methods for handling this process. There are three main benefits to using this method:

1. No long loops that can slow down performance.
2. Handles leading zero's easily.
3. As mentioned in the Tech Tip, the local separator for decimal values does not matter. You can use the 4D v11 SQL command GET SYSTEM FORMAT with the Decimal separator constant to get around this, but this method works without it very elegantly.