如何将整数整数值转换为3位点分隔字符串

Giz*_*eat 5 delphi freepascal string-formatting

我不敢相信我为此付出了很多努力!希望这是一件容易的事。使用Delphi或Freepascal:

Given the whole integer value "1230", or "1850", how do you format that as a floating point string of 3 digits where the decimal is in the 3rd position, and the trailing digit discarded.

Example

1230 means "v12.3" 1850 means "v18.5"

So I need to convert the first two digits to a string. Then insert a decimal place. Convert the third digit to a string after the decimal place. And discard the zero. I've looked at Format, FormatFloat, Format, and several others, and they all seem to equate to taking existing floating point numbers to strings, or floating point strings to numbers.

LU *_* RD 8

Just assign your integer value to a float and divide by 100.0.

Use Format() or FormatFloat() to convert the value to a string with three digits and a decimal point:

program Project8;

{$APPTYPE CONSOLE}

uses
  System.SysUtils;

var
  i : Integer;
const
  myFormat : TFormatSettings = (DecimalSeparator: '.');
begin
  i := 1230;
  WriteLn(Format('v%4.1f',[i/100.0],myFormat));   // Writes v12.3
  WriteLn(FormatFloat('v##.#',i/100.0,myFormat)); // Writes v12.3
  ReadLn;
end.
Run Code Online (Sandbox Code Playgroud)


Dav*_*nan 8

当整数算术可以完成工作时,我个人不太在意使用浮点算术(在其他答案中看到的除以10的方法)。您正在将数字转换为不完美的表示形式,然后四舍五入到小数点后一位。这些解决方案将起作用,因为您可以对表示的准确性施加足够的限制。但是,当可以使用整数运算精确完成算术运算时,为什么还要触发浮点数呢?

因此,我总是会选择这些路线上的东西。

Major := Version div 100;
Minor := (Version mod 100) div 10;
Run Code Online (Sandbox Code Playgroud)

Version您的输入值在哪里。然后可以将其转换为如下所示的字符串:

VersionText := Format('%d.%d', [Major, Minor]);
Run Code Online (Sandbox Code Playgroud)

您甚至可以在没有任何显式算法的情况下进行转换:

VersionText := IntToStr(Version);
N := Length(VersionText);
VersionText[N] := VersionText[N-1];
VersionText[N-1] := '.';
Run Code Online (Sandbox Code Playgroud)